迴圈排序 Python 程式


在本文中,我們將瞭解如何解決以下問題陳述。

問題陳述 − 已提供一個數組,我們需要使用迴圈排序的概念對它進行排序。

這是一個就地演算法,交換透過形成迴圈來進行。

現在讓我們觀察以下實施中的解決方案 -

例如

 線上演示

def cycleSort(array):
   writes = 0
   # cycles to be rotated
   for cycleStart in range(0, len(array) - 1):
      item = array[cycleStart]
      #position to place the item
      pos = cycleStart
      for i in range(cycleStart + 1, len(array)):
         if array[i] < item:
            pos += 1
      # if item exits, it is not a cycle
      if pos == cycleStart:
         continue
      # Otherwise, place the item
      while item == array[pos]:
         pos += 1
      array[pos], item = item, array[pos]
      writes += 1
      # rotation continued
      while pos != cycleStart:
         # Find a position to place the item
         pos = cycleStart
         for i in range(cycleStart + 1, len(array)):
            if array[i] < item:
               pos += 1
         # place the item
         while item == array[pos]:
            pos += 1
         array[pos], item = item, array[pos]
         writes += 1
   return writes
# main
arr = [1,5,3,4,8,6,3,4,5]
n = len(arr)
cycleSort(arr)
print("Sorted array is : ")
for i in range(0, n) :
   print(arr[i], end = " ")

輸出

Sorted array is :
1 3 3 4 4 5 5 6 8

所有變數都在區域性範圍內宣告,並且上圖中可以看到它們的引用。

總結

在本文中,我們學習瞭如何為迴圈排序編寫 Python 程式

更新於: 2019 年 12 月 20 日

226 次瀏覽

開啟您的 事業

完成課程並獲得認證

立即開始
廣告