📜  循环排序的Python程序

📅  最后修改于: 2021-04-27 18:00:57             🧑  作者: Mango

循环排序是一种就地排序算法,一种不稳定的排序算法,一种比较排序,在理论上,对原始数组的写入总数在比较上是最佳的。

  • 就内存写入次数而言,这是最佳的。它最大程度地减少了要排序的内存写操作的数量(每个值要么被写入零次(如果它已经处于其正确位置,要么被写入一次至其正确位置)。)
  • 基于这样的思想,可以将要排序的数组划分为多个循环。周期可以显示为图表。如果在排序数组中第i个索引处的元素必须出现在第j个索引处,则我们有n个节点和从节点i指向节点j的边。
    以arr [] = {4,5,2,1,5}循环
    循环排序

    以arr [] = {4,3,2,1}循环
    cyclc-sort2

我们一个接一个地考虑所有周期。我们首先考虑包含第一个元素的循环。我们找到第一个元素的正确位置,将其放置在正确的位置,例如j。我们考虑arr [j]的旧值并找到其正确位置,直到当前循环的所有元素都放置在正确位置之前,我们一直这样做,即,我们不回到循环起点。

Python3
# Python program to impleament cycle sort
  
def cycleSort(array):
  writes = 0
    
  # Loop through the array to find cycles to rotate.
  for cycleStart in range(0, len(array) - 1):
    item = array[cycleStart]
      
    # Find where to put the item.
    pos = cycleStart
    for i in range(cycleStart + 1, len(array)):
      if array[i] < item:
        pos += 1
      
    # If the item is already there, this is not a cycle.
    if pos == cycleStart:
      continue
      
    # Otherwise, put the item there or right after any duplicates.
    while item == array[pos]:
      pos += 1
    array[pos], item = item, array[pos]
    writes += 1
      
    # Rotate the rest of the cycle.
    while pos != cycleStart:
        
      # Find where to put the item.
      pos = cycleStart
      for i in range(cycleStart + 1, len(array)):
        if array[i] < item:
          pos += 1
        
      # Put the item there or right after any duplicates.
      while item == array[pos]:
        pos += 1
      array[pos], item = item, array[pos]
      writes += 1
    
  return writes
    
#  driver code 
arr = [1, 8, 3, 9, 10, 10, 2, 4 ]
n = len(arr) 
cycleSort(arr)
  
print("After sort : ")
for i in range(0, n) : 
    print(arr[i], end = \' \')
  
# Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:After sort : 
1 2 3 4 8 9 10 10 
Please refer complete article on Cycle Sort for more details!