Python sorting algorithm

Keywords: Python less

Python sorting algorithm

All the following sorting methods will use the swap function to exchange the positions in the two lists. The code is as follows:

def swap(lyst,i,j):
    temp = lyst[i]
    lyst[i]=lyst[j]
    lyst[j]=temp

1. Select Sorting:

Principle (integer list sorting from small to large): search the whole list first to find the position subscript of the smallest item. If it is not the first item, then adjust the position of the first item to the position of the smallest item, and then search the second item to the last item. Repeat the operation.

General process:

Unsorted list After the first round After the second round After the third round After the fourth round
5 1* 1 1 1
3 3 2* 2 2
1 5* 5 3* 3
2 2 3* 5* 4*
4 4 4 4 5*
def selectionSort(lyst):
    i=0
    while i < len(lyst) -1:#Do n-1 searches
        minIndex = i#The first item in the search scope is the smallest
        j = i + 1
        while j < len(lyst):#Start search
            if lyst[j] < lyst[minIndex]:
                minIndex = j
            j += 1
        if minIndex != i:#If the first item and the smallest item are not the same, exchange the two items
            swap(lyst,minIndex,i)
        i += 1

In this process, for a list of size n, the outermost loop executes n-1 times, the inner loop executes n-1 times for the first time, and n-2 times for the second time... The last n times, so a total of (n-1)+(n-2) + +1=n(n-1)/2 times, time complexity is O(n^2)

2. Bubble sorting:

Strategy: start from the beginning of the list, and compare a pair of data items until they move to the end of the list. Whenever the order between the two pairs is not correct, the algorithm will exchange their positions. The effect of this process is to arrange the largest items to the end of the list in a bubbling way. Then, the algorithm repeats the process from the second item in the list to the last item in the list.

Unsorted list After round 1 After round 2 After round 3 After round 4
5 4* 4 4 4
4 5* 2* 2 2
2 2 5* 1* 1
1 1 1 5* 3*
3 3 3 3 5*

The python code is implemented as follows:

def bubbleSort(lyst):
    n=len(lyst)
    while n > 1:#After execution, n-1 bubbling is required
        i = 1#Start bubble sorting
        while i < n:
            if lyst[i] < lyst[i-1]:#If the preceding term is greater than the following term, the two terms are exchanged
                swap(lyst,i,i-1)
            i += 1
        n -= 1

The outer side must execute n-1 times, and the inner side must execute from n-1 times to 1 time, so the time complexity is the same as the selection and sorting, both of which are O (n^2)

This algorithm has an improvement. By setting a bool type flag in advance, if the swap function is called, the bool changes the value, but if not, the function exits directly. In the best case, you only need to traverse the data once, but the average and worst case is O (n^2). The code is as follows:

def bubbleSort(lyst):
    n=len(lyst)
    while n > 1:
        swapped = False
        i = 1
        while i < n:
            if lyst[i] < lyst[i-1]:
                swap(lyst,i,i-1)
                swapped = True
            i += 1
      if not swapped:return
      n -= 1

3. Insert sort:

Insert sort works like many people sort a hand of poker. At first, our left hand was empty and the cards on the table were facing down. Then, we take a card from the table one at a time and insert it in the right position in the left hand. To find the right position for a card, we compare it from right to left with each card that is already in hand. The cards on the left hand are always in order. They are the cards at the top of the pile on the table

Insert sorting refers to that in the elements to be sorted, assuming that the number of the first n-1 (where n > = 2) has been arranged, now insert the nth number into the previously arranged sequence, and then find the appropriate position, so that the sequence of the nth number inserted is also arranged in order. The process of inserting all elements according to this method until the whole sequence is ordered is called insertion sorting

This understanding may be somewhat abstract. Let's show it directly with icons:

Unsorted list After round 1 After round 2 After round 3 After round 4
2 2 1* 1 1
5← 5 (not inserted) 2 2 2
1 1← 5 4* 3*
4 4 4← 5 4
3 3 3 3← 5

Code implementation:

def insertionSort(lyst):#It can be imagined as the process of sorting out the cards in hand when playing against the landlord
    i = 1
    while i < len(lyst):
        itemToInsert = lyst[i]#It's like taking out the cards
        j=i-1
        while j >= 0:#Compared with all the cards in front of it, if there is a card larger than the card taken out, the card taken out will be inserted in the front position of the card larger than it
            if itemToInsert < lyst[j]:
                lyst[j+1] = lyst[j]
                j -= 1
            else:break
        lyst[j+1] = itemToinsert
        i += 1

Assuming that all items are unsorted (for example, 54321), it still needs to traverse every item in the same way as selection sorting, with a complexity of O (n^2). However, if there are ordered items, the complexity will be reduced. The more ordered items are, the lower the complexity is. When all items are ordered, the complexity is O(n)

4. Quick sorting

The main idea is to divide and rule, divide a list into different parts, and use recursion to solve it (more abstract, video recommended)

def quicksort(array)
	if len(array)<2:
        return array
    else:
        baseValue=array(0)
        less=[m for m in array[1:] if m < baseValue]
        eqal=[w for w in array if w==baseValue]
        greater=[n for n in array[1:] if n >baseValue]
    return quickSort(less)+equal+quickSort(greater)

5. Merge and sort

# Record merging and sorting
def MergeSort(lists):
    if len(lists) <= 1:
        return lists
    middle = len(lists)//2
    left = MergeSort(lists[:middle])
    right = MergeSort(lists[middle:])
    return merge(left, right)


def merge(a, b):
    c = []
    h = j = 0
    while j < len(a) and h < len(b):
        if a[j] < b[h]:
            c.append(a[j])
            j += 1
        else:
            c.append(b[h])
            h += 1
    if j == len(a):
        for i in b[h:]:
            c.append(i)
    else:
        for i in a[j:]:
            c.append(i)

    return c

Posted by efegue on Thu, 18 Jun 2020 22:36:23 -0700