Stable and non-stable sort sort

Reference article link: http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/

stable

Bubble sort (bubble sort) - O (n2 )
insertion sort (insertion sort) - O (n2 )
merge sort (merge sort) - O (n log n)
  

Unstable

Selection Sort (selection sort) - O (n2 )
Hill sorting (shell sort) - O (n log n)
HEAPSORT (heapsort) - O (n log n)
quicksort (quicksort) - O (n log n)

Bubble Sort (adjacent to the exchange)

Fundamental

1. Comparison of the adjacent elements. If the first is greater than the second, the two of them exchanged.
2. do the same for the first 0 to the n-1 data. At this time, the largest number on the "float" to the last position on the array.
3. Repeat the above steps for all elements, except the last one.
4. Repeat the above steps every time duration of fewer and fewer elements, until there is no need to compare a pair of numbers.
A trip traversing If no data exchange, then already sorted, so no need to iterate a. With a flag to record this status.

#冒泡排序
def bubble_sort(arry):
    n = len(arry)
    for i in range(n-1,0,-1):
        flag = 1
        for j in range(0,i):
            if arry[j] > arry[j+1]:
                arry[j],arry[j+1] = arry[j+1],arry[j]
                flag = 0
        if flag:
             break
    return arry
if __name__ == '__main__':
    disorder_arry  = [10,9,8,7,6,5,4,3,2,1]
    order_arry = bubble_sort(disorder_arry)
    print(order_arry)
#某一趟遍历如果没有数据交换,则说明已经排好序了,因此不用再进行迭代了。用一个标记记录这个状态即可。

Sorting selection (selecting the minimum exchange)

#选择排序
def select_sort(arry):
    n = len(arry)
    for i in range(0,n):
        min = i
        for j in range(i+1,n):
            if arry[j] < arry[min]:
                min = j
        arry[min],arry[i] = arry[i],arry[min]
    return arry

if __name__ == '__main__':
    disorder_arry  = [3,2,1]
    order_arry = select_sort(disorder_arry)
    print(order_arry)

Insertion sort (insert elements into an ordered array)

Fundamental

1. Starting from the first element, which can be considered to have been sorted
2. Remove the next element, the forward scan from the sequence of elements has been ordered in
3. If the scanned elements (sorted) is greater than the new element, after the move an element
3, until it finds the sorted element positions equal to or less than the new element 4. repeat step
5. after the new element is inserted into the position
6. repeat steps 2 to 5

#插入排序
def insert_sort(arry):
    n = len(arry)
    for i in range(1,n):
        if arry[i] < arry[i-1]:
            temp = arry[i]
            index = i
            for j in range(i-1,-1,-1):
                if arry[j] > temp:
                    arry[j+1] = arry[j]
                    index = j
                else:
                    break
            arry[index] = temp
    return arry

if __name__ == '__main__':
    disorder_arry  = [3,2,1,4]
    order_arry = insert_sort(disorder_arry)
    print(order_arry)

Shell sort

Fundamental

Hill sort, also known as incremental descending sorting algorithm, in essence, is a packet insertion sort. Proposed by Donald Shell in 1959. Hill sorting non-stationary sorting algorithm.

Hill is the basic idea of ​​the sort: the array of columns and column insertion sort are in a table, repeat this process, but each time with a longer column (step longer, less the number of columns) to . Finally, the entire table is only one of. Convert the array to the table in order to better understand this algorithm, the algorithm itself or use an array to be sorted.

For example, assume there is such a set of numbers [1,314,943,382,255,994 6,523,452,773,253,910], if we start step is 5 sorts, we have placed these lists by 5 the table to better describe the algorithm, so they should look like this:

33 is 82 14 94 13 is
25 59 23 is 94 65
45 27 25 39 73 is
10
and then we sorted for each column:

23 is 73 is 25 14 10
13 is 27 39 94 33 is
25 59 94 65 82
45
When four lines above figures, sequentially together we get: [1,014,732,523,132,794 3,339,255,994,658,245]. Case 10 has been moved to the correct position, and then to step 3 to sort:

73 is 14 10
25 23 is 13 is
27 94 33 is
39 25 59
94 65 82
45
after sorting becomes:

13 is 14 10
25 23 is 33 is
27 25 59
39 65 73 is
45 94 82
94
Finally, a sorting step (at this time is a simple insertion sort).

def shell_sort(ary):
    n = len(ary)
    gap = round(n/2)       #初始步长 , 用round四舍五入取整
    while gap > 0 :
        for i in range(gap,n):        #每一列进行插入排序 , 从gap 到 n-1
            temp = ary[i]
            j = i
            while ( j >= gap and ary[j-gap] > temp ):    #插入排序
                ary[j] = ary[j-gap]
                j = j - gap
            ary[j] = temp
        gap = round(gap/2)                     #重新设置步长
    return ary

Merge sort (recursive partitioning the array, and then combined)

def merge_sort(ary):
    if len(ary) <= 1 : return ary
    num = int(len(ary)/2)       #二分分解
    left = merge_sort(ary[:num])
    right = merge_sort(ary[num:])
    return merge(left,right)    #合并数组

def merge(left,right):
    '''合并操作,
    将两个有序数组left[]和right[]合并成一个大的有序数组'''
    l,r = 0,0           #left与right数组的下标指针
    result = []
    while l<len(left) and r<len(right) :
        if left[l] < right[r]:
            result.append(left[l])
            l += 1
        else:
            result.append(right[r])
            r += 1
    result += left[l:]
    result += right[r:]
    return result

Quick Sort

def quick_sort(arry):
    return qsort(arry,0,len(arry)-1)

def qsort(arry,left,right):#[3,2,1,4]
    if left >= right:
        return arry
    key = arry[left]#3
    lp = left#0
    rp = right#3
    while lp < rp:
        while arry[rp] >= key and lp < rp:
            rp -=1
        while arry[lp] <= key and lp <rp:
            lp +=1
        arry[lp],arry[rp] = arry[rp],arry[lp]
    arry[left],arry[lp] = arry[lp],arry[left]
    qsort(arry,left,lp-1)
    qsort(arry,rp+1,right)
    return arry
if __name__ == '__main__':
    disorder_arry  = [3,2,1,4]
    order_arry = quick_sort(disorder_arry)
    print(order_arry)

Heapsort

def heap_sort(ary) :
    n = len(ary)
    first = int(n/2-1)       #最后一个非叶子节点
    for start in range(first,-1,-1) :     #构造大根堆
        max_heapify(ary,start,n-1)
    for end in range(n-1,0,-1):           #堆排,将大根堆转换成有序数组
        ary[end],ary[0] = ary[0],ary[end]
        max_heapify(ary,0,end-1)
    return ary


#最大堆调整:将堆的末端子节点作调整,使得子节点永远小于父节点
#start为当前需要调整最大堆的位置,end为调整边界
def max_heapify(ary,start,end):
    root = start
    while True :
        child = root*2 +1               #调整节点的子节点
        if child > end : break
        if child+1 <= end and ary[child] < ary[child+1] :
            child = child+1             #取较大的子节点
        if ary[root] < ary[child] :     #较大的子节点成为父节点
            ary[root],ary[child] = ary[child],ary[root]     #交换
            root = child
        else :
            break

Guess you like

Origin www.cnblogs.com/levylovepage/p/11563327.html