1. insertion sort, O(n^2)
def insertion_sort(array):
n=len(array)
for i in range(1,n):
for j in range(i,0,-1):
if array[j]<array[j-1]:
array[j],array[j-1]=array[j-1],array[j]
else:
break #前面的数更小,不用再比较
return array
print(insertion_sort([4,5,6,7,1,2]))
2. bubble sort, ?(?^2)
def bubble_sort_1(array):
n=len(array)
for i in range(n):
for j in range(n-1-i): #larger j already sorted(bubble to surface)
if array[j]>array[j+1]:
array[j],array[j+1]=array[j+1],array[j]
return array
def bubble_sort_2(array):
n=len(array)
while True:
swapped=False
for j in range(n-1):
if array[j]>array[j+1]:
array[j], array[j + 1] = array[j + 1], array[j]
swapped=True
if swapped==False:
break
return array
print(bubble_sort_1([4,5,6,7,1,2]))
print(bubble_sort_2([4,5,6,7,1,2]))
3. quick sort (left+pivot+right)
- Average: ?(?log?) (if not unluckily too bad pivot)
- Worst: O(n^2). E.g. [5, 4, 3, 2, 1, 0]
def quicksort(array):
if len(array)<2:
return array
pivot = array[0] #just choose 1st number as pivot
left=[i for i in array[1:] if i<=pivot]
right=[i for i in array[1:] if i>pivot]
return quicksort(left)+[pivot]+quicksort(right)
print(quicksort([4,5,6,7,1,2]))
- How to choose pivot? The first: simplest and fine. But bad if list already ordered
- Median of list: an additional ?(?) search, not used
4. merge sort, avg O(nlogn), even the worst O(nlogn)
def merge_sort(array):
if len(array)<=1:
return array
mid =(len(array)+1)//2
sub1=merge_sort(array[:mid])
sub2=merge_sort(array[mid:])
return ordered_merge(sub1,sub2)
def ordered_merge(a1,a2):
cnt1,cnt2=0,0
result=[]
while cnt1<len(a1) and cnt2 < len(a2):
if a1[cnt1]<a2[cnt2]:
result.append(a1[cnt1])
cnt1+=1
else:
result.append(a2[cnt2])
cnt2+=1
result+=a1[cnt1:]
result+=a2[cnt2:]
return result
print(merge_sort([4,5,6,7,1,2]))