# Algorithm sort algorithm Python

Time：2022-6-20

Python sorting algorithm: insert sort, bubble sort, merge sort, quick sort, etc.

Sorting algorithms: insert sort, bubble sort, merge sort, quick sort, etc.

Sorting algorithm: insert sort, bubble sort, merge sort, quick sort, etc.

Sorting algorithms: insert sort, bubble sort, merge sort, quick sort, etc.

# Sorting algorithms

Diagram of each sorting algorithmhttps://blog.csdn.net/qq_37941471/article/…

## Bubble sort o (n^2) O (1)

Bubble sort is a simple sort algorithm. It iterates over the sequence to be sorted, comparing two elements at a time,

If they are in the wrong order, exchange them. The work of traversing a sequence of numbers is repeated until there is no need to exchange, that is, the number

The column has been sorted.

• Compare adjacent elements. If the first is larger (in ascending order) than the second, swap them.
• Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step, the last element will be the maximum number.
• Repeat the above steps for all elements except the last one.
• Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.
``def bubble_ sort(nums):``

## Insert sortinsert sort o (n^2) O (1)

Insertion sort (English: insertion sort) is a simple and intuitive sorting algorithm.

• By constructing an ordered sequence, for unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert.
• In the implementation of insert sorting, in the process of scanning from back to front, the sorted elements need to be moved back step by step repeatedly to provide insertion space for the latest elements.
``````def insert_sort(nums):
for i in range(1, len(nums)):
for j in range(i, 0, -1):
if nums[j] < nums[j - 1]:
nums[j], nums[j - 1] = nums[j - 1], nums[j]

if __name__ == '__main__':
nums = [54, 26, 93, 17, 77, 31, 44, 55, 20]
insert_sort(alist)
print(alist)``````

## Selection sort o (n^2) O (1)

Selection sort is a simple and intuitive sorting algorithm. Its working principle is as follows. First, find the smallest (large) element in the unordered sequence,

Store it at the beginning of the sorting sequence, and then continue to find the smallest (large) element from the remaining unordered elements, and then put it at the end of the sorted sequence.

And so on until all the elements are sorted.

• The main advantage of selective sorting relates to data movement. If an element is in the correct final position, it will not be moved.
• Select sort to exchange a pair of elements at a time,
• At least one of them will be moved to its final position, so the table of n elements will be sorted and exchanged at most n-1 times in total.
• Among all the sorting methods that rely entirely on exchange to move elements, selective sorting is a very good one.
``def selection_ sort1(nums):``

## Quick sort o (nlogn) O (logn)

The data to be sorted is divided into two independent parts by one sorting. All the data in one part is smaller than that in the other part,

Then, the two parts of data are quickly sorted according to this method. The whole sorting process can be recursive, so that the whole data becomes an ordered sequence.

Recursive implementation

``def quick_ sort(nums, start, end):``

## Merge sort o (nlogn) O (logn)

Divide the elements in array[0,…, n-1] into two sub arrays: array1[0,…, n/2]

And array2[n/2+1,…, n-1]. Sort the two arrays separately, and then sort the sorted

The two subarrays are merged into an ordered array with n elements

• Recursive implementation
• When the array length is relatively short, other sorting schemes, such as insert sorting, are selected instead of recursion
• In the merging process, the subscript of the record array can be used instead of applying for new memory space; To avoid frequent data movement between array and auxiliary array
``Def merge (left, right): \``

## Heap sort o (nlogn) O (logn)

Heap sort is a kind of tree selection sort, which is an effective improvement on direct selection sort.

• Initially, the sequence of numbers to be sorted is regarded as a binary tree stored in sequence, and their storage order is adjusted to make it a heap,
• At this time, the number of root nodes of the heap is the largest. The root node is then swapped with the last node of the heap. Then readjust the previous (n-1) number to make it a heap.
• And so on, until the heap has only two nodes, and exchange them, and finally get an ordered sequence with n nodes. From the description of the algorithm,
• Heap sorting requires two processes: one is to create a heap, and the other is to exchange positions between the top of the heap and the last element of the heap. So heap sorting consists of two functions.
• The first is the heap building permeating function, and the second is the function that repeatedly calls the permeating function to realize sorting.

Under the definition of heap: a sequence (H1, H2,…, HN) with n elements is called heap if and only if it meets (hi>=h2i, hi>=2i+1) or (hi<=h2i, hi<=2i+1) (i=1,2,…, n/2).

Only the heap satisfying the former condition is discussed here. It can be seen from the definition of heap that the top element of heap (i.e. the first element) must be the largest item (large top heap).

A complete binary tree can visually represent the structure of the heap. The heap top is the root, and the others are the left subtree and the right subtree.

``#Adjust the heap, and adjust the maximum value to the top of the heap``

## Hill sort Shell sort o (n^ (1.3))) O (1)

Shell sort is also a kind of insert sort. Also known as reduced incremental sort, it is a more efficient and improved version of the direct insertion sort algorithm.

Hill sort is an unstable sort algorithm. This method is based on dl Shell was proposed in 1959.

• The column to be sorted is divided into several groups, and insertion sorting is carried out in each group to make the whole sequence basically orderly, and then insertion sorting is carried out for the whole sequence.
``````def shell_sort(nums):
size = len(nums)
gap = size >> 1
while gap > 0:
for i in range(gap, size):
j = i
while j >= gap and nums[j - gap] > nums[j]:
nums[j - gap], nums[j] = nums[j], nums[j - gap]
j -= gap
gap = gap >> 1

if __name__ == '__main__':
nums = [54, 26, 93, 17, 77, 31, 44, 55, 20]
shell_sort(nums)
print(nums)``````

Cardinal sorting is a non comparative integer sorting algorithm. Its principle is to cut an integer into different numbers according to the number of digits, and then compare them according to each digit. Since integers can also express strings (such as names or dates) and floating-point numbers in a specific format, cardinality sorting is not limited to integers.

• The time spent in the algorithm is basically to allocate elements to the bucket and string elements from the bucket; Allocate elements to the bucket: cycle length times;

-String elements from the bucket: this calculation is a bit troublesome. It seems that there are two cycles. In fact, the second cycle is determined by the elements in the bucket, which can be expressed as: K × buckerCount； Where k represents the number of elements in a bucket, and buckercount represents the number of buckets in which elements are stored;

-There are several special cases:

-First, all elements are stored in a bucket: k = length, buckercount = 1;

-Second, all elements are equally allocated to each bucket: k = length/ buckercount, buckercount = 10; (10 barrels have been fixed here)

-Therefore, the average time taken to collect the part is: length (i.e. element length n)

-To sum up: the time complexity is: poscount(length  + length) ； Where poscount is the highest digit of the largest element in the array; Simplified: O (kn ) ； Where k is a constant and N is the number of elements;

Cardinality sort vs count sort vs bucket sort

1. These three sorting algorithms all use the concept of bucket, but there are obvious differences in the use of bucket:
2. Cardinality sorting: allocate buckets according to each number of the key value;
3. Counting and sorting: each bucket only stores the single key value;
4. Bucket sorting: each bucket stores a certain range of values;

``def radix_ sort(s):``

## Count sort o (n+k)

The core of counting and sorting is to convert the input data values into keys and store them in the extra array space. As a sort of linear time complexity, count sort requires that the input data must be integers with a certain range.

``def countSort(arr):``

## Bucket sorting BUCKETSORT o (m), where m is the number of buckets

Bucket sorting is an upgraded version of counting sorting. It makes use of the mapping relationship of functions. The key to its efficiency lies in the determination of the mapping function. To make bucket sorting more efficient, we need to do these two things:

Increase the number of barrels as much as possible with sufficient additional space

The mapping function used can evenly distribute the input n data into k buckets

At the same time, for the sorting of the elements in the bucket, it is very important to choose a comparison sorting algorithm for the performance.

1. When is the fastest

When the input data can be evenly distributed to each bucket.

2. When is the slowest

When the input data is allocated to the same bucket.

``def bucketSort(nums):``