Python - 排序演算法



排序是指以特定格式排列資料。排序演算法指定以特定順序排列資料的方式。最常見的順序是數值順序或字典順序。

排序的重要性在於,如果資料以排序方式儲存,則可以將資料搜尋最佳化到非常高的水平。排序還用於以更易讀的格式表示資料。下面我們看到五種在 Python 中實現排序的方法。

  • 氣泡排序

  • 歸併排序

  • 插入排序

  • 希爾排序

  • 選擇排序

氣泡排序

它是一種基於比較的演算法,其中比較每對相鄰元素,如果元素未按順序排列,則交換元素。

示例

def bubblesort(list):

# Swap the elements to arrange in order
   for iter_num in range(len(list)-1,0,-1):
      for idx in range(iter_num):
         if list[idx]>list[idx+1]:
            temp = list[idx]
            list[idx] = list[idx+1]
            list[idx+1] = temp
list = [19,2,31,45,6,11,121,27]
bubblesort(list)
print(list)

輸出

執行以上程式碼時,會產生以下結果:

[2, 6, 11, 19, 27, 31, 45, 121]

歸併排序

歸併排序首先將陣列分成相等的兩半,然後以排序的方式將它們組合起來。

示例

def merge_sort(unsorted_list):
   if len(unsorted_list) <= 1:
      return unsorted_list
# Find the middle point and devide it
   middle = len(unsorted_list) // 2
   left_list = unsorted_list[:middle]
   right_list = unsorted_list[middle:]

   left_list = merge_sort(left_list)
   right_list = merge_sort(right_list)
   return list(merge(left_list, right_list))

# Merge the sorted halves
def merge(left_half,right_half):
   res = []
   while len(left_half) != 0 and len(right_half) != 0:
      if left_half[0] < right_half[0]:
         res.append(left_half[0])
         left_half.remove(left_half[0])
      else:
         res.append(right_half[0])
         right_half.remove(right_half[0])
   if len(left_half) == 0:
      res = res + right_half
   else:
      res = res + left_half
   return res
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print(merge_sort(unsorted_list))

輸出

執行以上程式碼時,會產生以下結果:

[11, 12, 22, 25, 34, 64, 90]

插入排序

插入排序涉及在排序列表中找到給定元素的正確位置。因此,在開始時,我們比較前兩個元素並透過比較它們來排序它們。然後,我們選擇第三個元素,並在前兩個排序元素中找到其正確的位置。這樣,我們逐漸將更多元素新增到已經排序的列表中,方法是將它們放在其正確的位置。

示例

def insertion_sort(InputList):
   for i in range(1, len(InputList)):
      j = i-1
      nxt_element = InputList[i]
# Compare the current element with next one
   while (InputList[j] > nxt_element) and (j >= 0):
      InputList[j+1] = InputList[j]
      j=j-1
   InputList[j+1] = nxt_element
list = [19,2,31,45,30,11,121,27]
insertion_sort(list)
print(list)

輸出

執行以上程式碼時,會產生以下結果:

[19, 2, 31, 45, 30, 11, 27, 121]

希爾排序

希爾排序涉及對彼此遠離的元素進行排序。我們對給定列表的大子列表進行排序,並不斷減小子列表的大小,直到所有元素都被排序。以下程式透過將其設定為列表大小的一半來找到間隙,然後開始對其中的所有元素進行排序。然後,我們不斷重置間隙,直到整個列表都被排序。

示例

def shellSort(input_list):
   gap = len(input_list) // 2
   while gap > 0:
      for i in range(gap, len(input_list)):
         temp = input_list[i]
         j = i
# Sort the sub list for this gap
   while j >= gap and input_list[j - gap] > temp:
      input_list[j] = input_list[j - gap]
      j = j-gap
      input_list[j] = temp
# Reduce the gap for the next element
   gap = gap//2
list = [19,2,31,45,30,11,121,27]
shellSort(list)
print(list)

輸出

執行以上程式碼時,會產生以下結果:

[2, 11, 19, 27, 30, 31, 45, 121]

選擇排序

在選擇排序中,我們首先在給定列表中找到最小值,並將其移動到排序列表中。然後,我們對未排序列表中的每個剩餘元素重複此過程。進入排序列表的下一個元素與現有元素進行比較,並放置在其正確的位置。因此,最終未排序列表中的所有元素都將被排序。

示例

def selection_sort(input_list):
   for idx in range(len(input_list)):
      min_idx = idx
      for j in range( idx +1, len(input_list)):
         if input_list[min_idx] > input_list[j]:
            min_idx = j
      # Swap the minimum value with the compared value
      input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]
l = [19,2,31,45,30,11,121,27]
selection_sort(l)
print(l)

輸出

執行以上程式碼時,會產生以下結果:

[2, 11, 19, 27, 30, 31, 45, 121]
廣告

© . All rights reserved.