Six sorts python

Six sorts

1 select sort

  • Idea: first record the subscript k of the first element to be sorted, and then select the smallest element less than data[k] from the records to be sorted each time, and place it at the end of the ordered sub table until all sorting is completed
  • Time complexity: O(n^2)
  • Space complexity: O(1)
  • Stability: unstable
def select_sort(data):
    n=len(data)
    for i in range(n-1):
        min=i
        for j in range(i+1,n):
            if data[min]>data[j]:
                min=j
        if min!=i:
            data[i],data[min]=data[min],data[i]
    return data
select_sort([1,3,5,2,4])
[1, 2, 3, 4, 5]

2 bubble sorting

  • Idea: the head of the array is regarded as the water surface, the tail of the array is regarded as the water bottom, and the smallest (or largest) element floats (or sinks) until the end. The idea is to compare the element size and then exchange the element values. Each time, the smallest or largest element in the unordered elements is selected to reach the specified position.
  • Time complexity: in the best case, the array itself is positively ordered, O(n); In the worst case, the array is in reverse order, O(n2); The average time complexity is O(n2)
  • Space complexity: O(1)
  • Stability: stable
def maopao(data):
    n=len(data)
    for i in range(n-1):
        for j in range(i+1,n):
            if data[i]>data[j]:
                data[i],data[j]=data[j],data[i]
    return data
maopao([13,2,5,4])
[2, 4, 5, 13]

3 insert sort

  • Idea: divide the original sequence into ordered area and disordered area. Initially, data[0] forms an ordered area. Each external cycle inserts the first element of the disordered area into the appropriate position of the ordered area. At the same time, the element of the ordered area increases by 1 and the element of the disordered area decreases by 1, so that the element of the disordered area is 0
  • Time complexity: in the best case, the initial array is in positive order (incremental here), O(n); In the worst case, the initial array is in reverse order, O(n2); The average time complexity is O(n2)
  • Space complexity: O(1)
  • Stability: stable. When data[i]=datda[i-1], the relative position remains unchanged, so it is a stable sort
def insert(data):
    n=len(data)
    for i in range(1,n):
        for j in range(i,0,-1):
            if data[j]<data[j-1]:
                data[j]=data[j-1]
    return data

4. Hill sort

  • Idea: in essence, it belongs to insertion sorting, which is just to group the sequences first, and then insert them directly in the group. At the same time, the number of groups increases from more to less, the number of elements in the group increases from less to more, and the order changes from poor to good. Until the group spacing in the last step is 1, the array of direct insertion sorting has been basically ordered

  • Time complexity: O(nlogn) is about O(1.3n)

  • Space complexity: O(1)

  • Stability: unstable

def direct_insertion_sort(d):  # Insert sort directly. Because the subsequent Hill sort is used, it is converted to function
    d1 = [d[0]]
    for i in d[1:]:
        state = 1
        for j in range(len(d1) - 1, -1, -1):
            if i >= d1[j]:
                d1.insert(j + 1, i)  # Insert element into array
                state = 0
                break
        if state:
            d1.insert(0, i)
    return d1


def shell_sort(d):  # D is the out of order array, l is the initial increment, where l < len (d), and it is better to take len(d)/2. Finally, omit the length input directly
    length = int(len(d) / 2)  # 10
    num = int(len(d) / length)  # 2
    while 1:

        for i in range(length):
            d_mid = []
            for j in range(num):
                d_mid.append(d[i + j * length])
            d_mid = direct_insertion_sort(d_mid)
            for j in range(num):
                d[i + j * length] = d_mid[j]
        # print(d)
        length = int(length / 2)
        if length == 0:
            return d
            break
        # print('length:',length)
        num = int(len(d) / length)



d0 = [2, 15, 5, 9, 7, 6, 4, 12, 5, 4, 2, 64, 5, 6, 4, 2, 3, 54, 45, 4, 44]  # Original out of order d1 = shell_sort(d0)
shell_sort(d0)
[2, 2, 2, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7, 9, 12, 15, 44, 45, 54, 64]

5 quick sort

  • Idea: the idea of divide and conquer transforms big problems into small problems. The idea of recursion. The most important process is division. When the division is over, the array will be arranged in order. Quick sorting is a very important sort algorithm
    First, take a number from the sequence as the reference number (pivot). The partitioning process places all numbers larger than this number on its right, and all numbers less than or equal to it on its left. (ascending order) repeat the second step for the left and right intervals until there is only one number in each interval.
  • Time complexity: O(nlogn)
  • Stability: unstable
# Quick sort
def quick_sort(data):
    d=[[],[],[]]
    temp=data[-1]
    for i in data:
        if i<temp:
            d[0].append(i)
        elif i>temp:
            d[2].append(i)
        else:
            d[1].append(i)
    for d1 in d:
        if len(d1)>1:
            quick_sort(d1)
    d[0].extend(d[1])
    d[0].extend(d[2])
    return d[0]
quick_sort([1,3,546,676,8])
[1, 3, 8, 546, 676]

6 merge sort

  • Idea: the idea of divide and conquer is to divide the array into two groups A and B. if the data in these two groups are orderly, you can easily sort these two groups of data. Groups A and B can be divided into two groups respectively. By analogy, when the separated group has only one data, it can be considered that the group has reached order, and then merge the two adjacent groups. In this way, the merging sort is completed by first recursively decomposing the sequence and then merging the sequence

  • Time complexity: O(nlogn)

  • Stability: stable

def merge_sort(data):
    n=len(data)
    # 2 points
    mid=n//2
    d0=data[:mid]
    d1=data[mid:]
    if len(d0)>1:
        d0=merge_sort(d0)
    if len(d1)>1:
        d1=merge_sort(d1)
    for i in range(len(d1)):
        state=1
        for j in range(len(d0)):
            if d1[i]<d0[j]:
                state=0
                index=j+1
                d0.insert(j, d1[i])
                break
        if state==1:
            d0.extend(d1[1:])
            break
    return d0
d0 = [2, 15, 5, 9, 7, 6, 4, 12, 5, 4, 2, 64, 5, 6, 4, 2, 3, 54, 45, 4, 44]  
merge_sort(d0)
[2, 2, 2, 4, 4, 5, 5, 5, 6, 6, 9, 4, 5, 6, 5, 12, 2, 5, 6, 45]

Posted on Thu, 25 Nov 2021 17:49:38 -0500 by azunoman