Sorting Algorithms:InsertionSort/BubbleSort/QuickSort/MergeSort

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]))

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值