Python implementation ten kinds of classical sorting algorithm

1, bubble sort

The basic idea: a comparison of only two elements, the time complexity of the algorithm is THE ( n 2 ) O (n ^ 2)

def bub_sort(lists):
    n = len(lists)
    for i in range(n):
        for j in range(n):
            if lists[j-1] > lists[j]:
                lists[j-1],lists[j] = lists[j],lists[j-1]
    return lists

2, insertion sort

The basic idea: one is inserted into the data already sorted array, the time complexity of the algorithm is THE ( n 2 ) O (n ^ 2)

def insert_sort(lists):
    size = len(lists)
    for i in range(1,size):
        pivot = lists[i]
        j = i-1
        while j >= 0:
            if lists[j] > pivot:
                lists[j+] = list[j]
                lists[j] = pivot
            j -= 1
    return lists

3. Select the sort

The basic idea: Each time you select the smallest element into the current position

def select_sort(lists):
    n = len(lists)
    for i in range(n):
        for j in range(i:n):
            if lists[i] < lists[j]:
                lists[i],lists[j] = list[j],list[i]
    return lists

4, Hill sorting

An insertion sort

def shell_sort(lists):
    n = len(lists)
    dist = n//2
    while dist > 0:
        for i in range(dist,n):
            temp = lists[i]
            j = i
            while j >= dist and temp < lists[j - dist]:
                lists[j] = lists[j - dist]
                j -= dist
            lists[j] = temp
        dist //= 2
    return lists

5, merge sort

The basic idea: the idea of ​​divide and rule, first array is divided into two large arrays of small-scale, put two small arrays are sorted, and then combined. Time complexity of the algorithm THE ( n l o g n ) O (nlogn)

def merge_sort(lists):
    if len(lists) <=1:
        return lists
    mid = len(lists)//2
    left = merge_sort(lists[:mid])
    right = merge_sort(lists[mid:])
    return merge(left,right)
def mmerge(left,right):
    res = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            res.append(left[i])#append用于在列表末尾添加新内容
            i +=1
        else:
            res.append(right[j])
            j += 1
    res += left[i:]
    res += rught[j:]
    return res

6, heapsort

##堆排序
def heap_sort(lists):
    size = len(lists)
    build_heap(lists, size)
    for i in range(0, size)[::-1]:
        lists[0], list[i] = list[i], lists[0]
        adjust_heap(lists, 0, i)
    return lists

#堆调整
def adjust_heap(lists, i, size):
    lchild = 2 * i + 1
    rchild = 2 * i + 2
    maxi = i
    if lchild < size and lists[maxi] < lists[lchild]:
        maxi = lchild
    if rchild < size and lists[maxi] < lists[rchild]:
        maxi = rchild
    if maxi !=i:
    #在做了堆调整之后,做对调值操作
        lists[maxi],lists[i] = lists[i],lists[maxi]
        adjust_heap(lists, maxi, size)

#堆构建
def build_heap(lists,size):
    for i in range(0, int(size/2))[::-1]:
        adjust_heap(lists, i, size)

7, quick sort

The basic idea: Divide and conquer

def quick_sort(lists):
    less = []
    pivotlist = []
    more = []
    if len(lists) <= 1:
        return lists
    else:
        pivot = lists[0] #把第一个元素作为key
        for i in lists:
            if i < pivot:
                less.append(i)
            elif i > pivot:
                more.append(i)
            else:
                pivotlist.append(i)
        less = quick_sort(less)
        more = quick_sort(more)
    return less + pivotlist + more

def QuickSort(mylist,left,right):
    if left < right:
        i,j = left,right
        base = mylist[i]  #base作为基准数
        while (i < j):
            while (i < j) and (mylist[j] >= base):'''若列表后边的数比基准数大或相等,
                                                     则前移一位直到有比基准数小的数出现'''
                j = j - 1
            mylist[i] = mylist[j]#如找到,则把第j个元素赋值给第i个元素,此时列表中i,j的元素相等
            while (i < j) and (mylist[i] <= base):#同样的方式比较前半区
                i = i + 1
            mylist[j] = mylist[i]
        mylist[i] = base
        
        #递归前后半区
        QuickSort(mylist, left, i-1)
        QuickSort(mylist, j + 1, right)
    return mylist

8, counting sequencing

The basic idea: to an element of a, a check is less than several elements referred to as i, and the serial number into a position i

def count_sort(a,k):#a为数组,k为max(a)
    n = len(a)
    b = [0 for i in range(n)] #设置输出序列,并初始化为0
    c = [0 for i in range(k+1)] #设置计数序列并初始化为0
    for j in a:
        c[j] = c[j] + 1
    for i in range(1, len(c)):
        c[i] = c[i] + c[i-1]
    for j in a:
        b[c[j] - 1] = j
        c[j] = c[j] - 1
    return b

9, bucket sort

The basic idea: the array is divided into several sections of equal length, each sub-array respective sorting, and finally merge

def bucket_sort(a):
    buckets = [0] * ((max(a)-min(a))+1) #初始化桶元素为0
    for i in range(len(a)):
        buckets[a[i] - min(a)] +=1 #遍历数组a,在桶的相应位置累加值
        b = []
        for i in range(len(buckets)):
            if bucket[i] != 0:
                b += [i + min(a)] * buckets[i]
        return b

10, radix sort

The basic idea: the data to be sorted according to different cut-digit numbers, then the number of bits for each were compared

def radix_sort(list, d = 3): #默认三位数,可以自定义修改
    for i in range(d): #d轮排序
        s = [[] for k in range(10)] #因为每一位数字都是0-9,所以建10个桶
        for j in list:
            s[int(j / (10 ** i)) % 10].append(j)
        re = [a for b in s for a in b]
    return re
Published 37 original articles · won praise 17 · views 2598

Guess you like

Origin blog.csdn.net/qq_44384577/article/details/104581668