Sorting Algoritm
Since learning to call the sort
function of C++
directly, I write less and less sort code. Therefore, this article is written to summarize several common sorting algorithms.
In this article, we will see the following sort:
- 🏌🏻Bubble Sort
- 🪂Insertion Sort
- 🐧Merge Sort
- 🦴Quick Sort
Bubble Sort
Time compesity O(n2)
General Ideas
Bubble sorting is one of the earliest sorting algorithms I came into contact with. Its main ideas are as follows:
-
A bubble compares all the elements in the sequence from the beginning to the end, and puts the largest one at the end.
-
All elements in the remaining sequence are compared again, with the largest at the end.
-
Repeat step 2.
Code Implementation(C)
1 | void Bubble_sort(int arr[], int size) |
Insertion Sort
Time compesity O(n2)
General Ideas
- In a group of numbers to be sorted, assume that the first n-1 (n > = 2)numbers are already in order.
- Insert the nth number into the previous ordinal number, so that the N numbers are also in order.
- Repeat this until all are in order.
Code Implementation ©
1 | void Insertion_Sort(int arr[], int size) |
Merge Sort
General Ideas
Merge sort is a sort method based on the idea of merge. The algorithm adopts the classic divide and conquer strategy .
- Divides the problem into some small problems.
- Recursively solves the small problems,
- “Repairs” the answers obtained in different stages.
Code Implementation ©
1 | void MSort(ElementType A[], ElementType TmpArray[], int Left, int Right) |
Quick Sort
General Ideas
- Base on 6.
- Use two sentries, one from right to left to find the first number smaller than 6, the other from left to right to find the first number larger than 6.
- Swap the two number. You have to look from right to left first.
- Repeat step 2 and step 3 until they meet each other.
- Swap the meet number and 6.
Code Implementation ©
1 | void Quicksort(ElementType A[], int N) |
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.