Python 精靈排序程式


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

問題陳述 - 我們給定一個數組,我們需要使用精靈排序對其進行排序。

演算法

1. Firstly we traverse the array from left to right.
2. Now,if the current element is larger or equal to the previous element then we traverse one step ahead
3. otherwise,if the current element is smaller than the previous element then swap these two elements and traverse one step back.
4. Repeat steps given above till we reach the end of the array

現在,讓我們觀察下面實現中的解決方案 −

示例

 線上演示

def gnomeSort( arr, n):
   index = 0
   while index < n:
      if index == 0:
         index = index + 1
      if arr[index] >= arr[index - 1]:
         index = index + 1
      else:
         arr[index], arr[index-1] = arr[index-1], arr[index]
         index = index - 1
   return arr
# main
arr = [1,4,2,3,6,5,8,7]
n = len(arr)
arr = gnomeSort(arr, n)
print ("Sorted sequence is:")
for i in arr:
   print (i,end=" ")

輸出

Sorted sequence is:
1 2 3 4 5 6 7 8

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

結論

在本文中,我們瞭解瞭如何製作一個用於精靈排序的 Python 程式

更新時間:20-12-2019

255 次觀看

開啟你的職業生涯

完成課程後獲得認證

立即開始
廣告