Python implements common sorting algorithms

1. Bubble sort

  • The bubble sort algorithm works as follows:

1. Compare adjacent elements, if the first is larger than the second, swap the two of them.
2. Do the same for each pair of adjacent elements, from the first row at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one.
4. Continue to repeat the above steps for fewer and fewer elements each time, until there are no pairs of numbers to compare.

  • time complexity:

If the initial state of the file is in positive order, one scan can complete the sorting, and the minimum time complexity is O(n).
If the initial state of the file is reversed, the maximum time complexity is O(n).

  • Stability: Bubble sort is a stable sorting algorithm.

  • Code:

#!/usr/bin/env python
#coding=utf-8
#BubbleSort
def BubbleSort(SortList):
    ListLength = len(SortList)
    while ListLength > 0:
        for i in range(ListLength - 1):
            if SortList[i] > SortList[i+1]:
                SortList[i] = SortList[i] + SortList[i+1]
                SortList[i+1] = SortList[i] - SortList[i+1]
                SortList[i] = SortList[i] - SortList[i+1]
        ListLength -= 1
    print SortList

if __name__ == '__main__':
    SortList = [6,5,4,3,2,1]
    BubbleSort(SortList)
  • Results of the:

/usr/bin/python2.7 /root/PycharmProjects/01/BubbleSort.py
[1, 2, 3, 4, 5, 6]

Process finished with exit code 0

2. Quick Sort

  • Basic idea:

Divide the data to be sorted into two independent parts by one sorting, and all the data in one part is smaller than all the data in the other part, and then quickly sort the two parts of the data according to this method. The whole sorting process can be recursive proceed so that the entire data becomes an ordered sequence.

  • Code:

def QuickSort(L,low,high):
    i = low
    j = high
    if i >= j:
        return L
    key = L[i]
    while i < j:
        while i < j and L[j] >=key:
            j -= 1
        L[i] = L[j]
        while i < j and L[i] <= key:
            i += 1
        L[j] = L[i]
    L[i] = key
    QuickSort(L,low,i-1)
    QuickSort(L,j+1,high)
    return L

if __name__ == '__main__':
    L = [6,5,4,8,2,1]
    QuickSort(L,0,len(L)-1)
    print L
  • Results of the:

/usr/bin/python2.7 /root/PycharmProjects/01/QuickSort.py
[1, 2, 4, 5, 6, 8]

Process finished with exit code 0

3. Merge Sort

  • basic idea

Merge sort is an efficient sorting algorithm based on the merge operation, which is a very typical application of the divide and conquer method. Combine the ordered subsequences to get a completely ordered sequence; that is, first make each subsequence ordered, and then make the subsequence segments ordered. If two ordered lists are merged into one ordered list, it is called Two-way merge.

  • How it works:
    Step 1: Apply for space so that the size is the sum of the two sorted sequences, and this space is used to store the merged sequence.
    Step 2: Set two pointers, and the initial positions are the starting positions of the two sorted sequences.
    Step 3: Compare the elements pointed to by the two pointers, select a relatively small element into the merge space, move the pointer to the next position, repeat the three steps until a pointer exceeds the end of the sequence, and put the remaining elements of the other sequence All elements are copied directly to the end of the merged sequence.

  • Comparison: Merge sort is a stable sort, the number of comparisons is less than that of quicksort, and the number of moves is more than that of quicksort.

  • Code:

def MergeSort(lists):
    if len(lists) <= 1:
        return lists
    num = int( len(lists) / 2 )
    left = MergeSort(lists[:num])
    right = MergeSort(lists[num:])
    return Merge(left,right)
def Merge(left,right):
    r, l=0, 0
    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
print MergeSort([1,2,3,4,5,6,7,88,99,18])
  • Results of the
/usr/bin/python2.7 /root/PycharmProjects/01/MergeSort.py
[1, 2, 3, 4, 5, 6, 7, 18, 88, 99]

Process finished with exit code 0

4. Bucket sorting

  • How Bucket Sort Works Divide
    the array into a limited number of buckets, and each bucket is sorted individually (it is possible to use another sorting algorithm or continue to use bucket sort to sort recursively). When the values ​​in the array to be sorted are evenly distributed, the bucket sort uses linear time O(n), but the bucket sort is not a comparison sort, and it is not affected by O(nlogn).

  • Summary:
    The average time complexity of bucket sorting is linear O(N+C), where C=N*(logN-logM). If relative to the same N, the larger the number of buckets M, the higher the efficiency. The best time complexity is O(N), and the space complexity of bucket sorting is O(N+M). If the input data is very large, and The number of buckets is also very large, the space cost is undoubtedly expensive, and the bucket sorting is stable.
    5. Insertion sort

  • Basic principle
    Insertion sort is to insert a piece of data into the ordered data that has been photographed to obtain a new ordered sequence with the number plus one. This algorithm is suitable for sorting a small amount of data and is a stable sorting algorithm.

  • Basic idea
    Each step inserts a record to be sorted into the appropriate position in the previously sorted file according to the size of its key value until all the records are inserted.

  • Classification:
    Direct Insertion Sort, Binary Insertion Sort (also known as Half Insertion Sort), Linked List Insertion Sort, Hill Sort (also known as Reduced Incremental Sort).

  • Direct Insertion Sort
    Direct Insertion Sort is a simple insertion sort, the basic idea of ​​which is to insert the records to be sorted into a sorted sorted sequence one by one according to the size of their key values, until all records are inserted. When finished, a new ordered sequence is obtained.

  • Half insertion sort
    (1) Calculate the middle point of 0 ~ i-1, and compare the element at the i index with the middle value. If the element at the i index is large, it means that the element to be inserted should be between the middle value and just added i Between the indexes, on the contrary, it is from the position at the beginning to the position of the middle value, which is very simple to complete the halving;
    (2) When finding the insertion position in the corresponding half range, continue to use the step (1) to shrink The range is halved continuously, and the range is reduced to 1/2 1/4 1/8 .... Quickly determine where the i-th element is to be inserted;
    (3) After determining the position, move the entire sequence back, and insert the element at the corresponding position.

  • Hill sorting method
    Hill sorting method is also known as shrinking incremental method. The basic idea of ​​Hill sorting method is: first select an integer, divide all records in the file to be sorted into groups, all records with a distance of are in the same group, and sort the records in each group. Then, take, repeat the above grouping and sorting work. When reaching=1, all records are sorted within the unified group.
    Sorting within each group is usually done by direct insertion. Since the value of s is large at the beginning, the number of records in each group is small, so the sorting is faster. With the continuous increase, the number of records in each group gradually increases, but because it has been sorted, the sorting speed is also relatively fast.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324740577&siteId=291194637