1. 程式人生 > 實用技巧 >Java中使用String作同步鎖

Java中使用String作同步鎖

歸併排序

這個系列是回顧之前所學,是用python商量著完成的。

路過的大佬就當看個樂,實現演算法的方式不一,也有討巧的做法。

我只講講我的思路,希望大家瀏覽的時候能多多提建議,共同學習共同進步。

--------------------------------------------------------------------------------------------------------

歸併排序的基本思想:

  歸併也稱之為合併,是將兩個或兩個以上的有序子表合併成一個有序表的過程,合併兩個子表也稱為二路合併。

舉個例子:

[5, 2, 1, 3, 6, 7]

地板除,向下取整

[5, 2, 1] 和 [3, 6, 7]

在此基礎上繼續二分

[5, 2] [1] [3] [6, 7]

將這些細分的陣列進行排序,然後將其一步步向上合併,最終得到有序的原序列

以下是具體實現:

 1 def merge_sort(list):
 2     n = len(list)
 3     if n <= 1:
 4         return list
 5     # 1.先找到陣列中的中心點的位置,以此作為二分的基礎
 6     pivot_index = n // 2
 7     # 2.既然是不斷的往下細分,就自然會想到用遞迴,而每次二分的依據便是上面的中心點
8 first_list = merge_sort(list[:pivot_index]) 9 second_list = merge_sort(list[pivot_index:]) 10 11 first_index = 0 12 second_index = 0 13 res = [] 14 while first_index < len(first_list) and second_index < len(second_list): 15 if first_list[first_index] < second_list[second_index]:
16 res.append(first_list[first_index]) 17 first_index += 1 18 else: 19 res.append(second_list[second_index]) 20 second_index += 1 21 res += first_list[first_index:] 22 res += second_list[second_index:] 23 24 return res