# Bubble sort, quick sort, merge sort, insert sort, hill sort, heap sort, count sort, bucket sort, cardinal sort

Source: Internet
Author: User
Tags sorts

Choose Sort, bubble sort, quick sort, merge sort, insert sort, hill sort, count sort, bucket sort, cardinal sort
These are some of the most commonly used sorting algorithms.

Select sort
for (int i = 0; i < n; i++) {
int minval = A[i];
int minid = i;
for (int j = i+1; J < N; j + +) {
if (A[j] < Minval) {
MiniD = j;
Minval = A[j];
}
}
Swap (A[i], A[minid]);
}
The simplest is to choose the sort, that is, each time the array is traversed, then the first small, the second small, know that the entire array is ascending and orderly. So the complexity of time is also very good to understand is O (n^2),

Bubble sort
Bubble sort when learning programming began to learn the first sort, at the beginning still find it difficult to understand, haha ~

Use two ideas, one at a time from the back to the next, a big sinking, or a small ascent from the past;

Big sinking, the biggest of the times will be on the right:

79404463

Include <bits/stdc++.h>

using namespace Std;
int n;
int a = {9, 19, 7, 2, 4, 5, 6, 8, 10, 11};
void Showarray () {
for (int i = 0; i < n; i++) {
cout << A[i] << "";
}
cout << Endl;
}
int main () {
CIN >> N;
n = 10;
for (int i = 0; i < n-1; i++) {//Up to N-1
for (int j = 0; J < N-1-i; J + +) {
if (A[j] > a[j + 1]) swap (A[j], a[j+1]);
}
}
Showarray ();
return 0;
}
Or a small float:

Include <bits/stdc++.h>

using namespace Std;
int n;
int a = {9, 19, 7, 2, 4, 5, 6, 8, 10, 11};
void Showarray () {
for (int i = 0; i < n; i++) {
cout << A[i] << "";
}
cout << Endl;
}
int main () {
CIN >> N;
n = 10;
for (int i = 0; i < n-1; i++) {//Up to N-1
for (int j = n-1; j > i; j--) {
if (A[j] < a[j-1]) swap (A[j], a[j-1]);
}
}
Showarray ();
return 0;
}
This shows the time Complexity O (n^2), but the best case (increment sequence), O (N*LGN)

Quick Sort
In general the time Complexity is O (N*LGN), but not stable, the worst is also O (n^2);

The quick row uses the divide to administer, the recursive thought, carries on the sorting;

The overall idea is to first define L = 0, r = len-1, two endpoints,

Each time you select the first number of the current array as the base point, and then in the case of L <=R, the number of right and left is exchanged continuously;

void QuickSort (int a[], int left, int. right) {
if (Left > right) return;
int base = A[left];

``int i = left,  j = right;while (i < j) {    while (i < j && a[j] >= base) j--;    while (i < j && a[i] <= base) i++;    swap(a[i], a[j]);}a[left] = a[i];a[i] = base;quickSort(a, left, i-1);quickSort(a, i+1, right);``

}
Merge sort
The so-called merge sort, that is, each time the two two sub-sequences are sorted, until the whole sequence, the beginning of the sub-sequence length is 1, and then continue to increment;

Time complexity O (N*LGN), more stable, preferably O (N)

void MergeSort () {
for (int step = 2; step/2 <= N; step *= 2) {
for (int i = 0; i < n; i + = Step) {
Sort (Tempori + i, Tempori + min (i + step, n));
}
}
}
Or the use of split-treatment recursion;

void Mergearray (int arr[], int from, int mid, int. to, int temp[]) {
int i = from;
int inter = mid + 1;
int k = 0;
while (from <= mid && Inter <= to) {
if (Arr[from] < Arr[inter])
temp[k++] = arr[from++];
Else
temp[k++] = arr[inter++];
}
while (from <= mid)
temp[k++] = arr[from++];
while (Inter <= to)
temp[k++] = arr[inter++];

``for (int j = 0; j < k; j++) {    arr[j + i] = temp[j];}``

}

void mergesort (int arr[], int from, int. to, int temp[]) {
if (from < to) {
int mid = (from + to)/2;
MergeSort (arr, from, Mid, temp);
MergeSort (arr, mid + 1, to, temp);
Mergearray (arr, from, mids, to, temp);
}
}

Insert Sort
Each time a new number is inserted in the sequence that is already ordered, and then the current is sorted, so that a small sequence is incremented in order each time the process is obtained;

Relatively stable, General complexity O (N*LGN), preferably O (N)

void Insertsort () {
for (int i = 1; i < n; i++) {
int temp = Tempori[i], j = i;
while (J > 0 && tempori[j-1] > Temp) {
TEMPORI[J] = tempori[j-1];
j--;
}
TEMPORI[J] = temp;
}
}
Hill sort
Hill sort when inserting a sort of upgraded version, there is a descending increment sequence, which is generally sorted by the array size n, constantly pressing the increment div of N/2, each time comparing the number of increments between these numbers, the number of these several sorts;

Time complexity uncertainty, instability, preferably O (N).

void Shellsort () {
int len = n;
for (int div = LEN/2; div >= 1; div = DIV/2) {
For each increment
for (int i = 0; I <= div; i++) {
for (int j = i; J < len-div; j + = div) {
for (int k = j; k < len; k + = div) {
if (Tempori[j] > Tempori[k]) {
Swap (Tempori[j], tempori[k]);
}
}
}
}
}
}

Heap Sort
Heap sorting is not very stable, then time complexity is generally o (N*LGN);

For a large heap, the top element of the heap is the largest, so after swapping it with the last element, the last element is the largest, and then the heap is adjusted in addition to the previous (later) size order. Loop so that the second-to-last number is the second largest, so you can get an increment sequence.

Therefore, it is required to increment the sequence, with the heap ordered with a large top heap, descending sequence, with the heap ordered by the small top heap.

The first is to build the heap, starting from the last non-leaf node to build up the heap, adjust, to ensure that each node is the root node of the sub-tree is the largest node of the right value. Introduction to the Actualize algorithm.

Adjust the large top pile, on the basis of the established good;
void Downajust (int low, int. high) {
int i = low, j = i2;//j for left child node
while (J <= High) {//There is a child node.
If there is a right child and the right child node value is greater than the value of the left child node
if (j + 1 <= High && heap[j + 1] > Heap[j]) {
j + +;
}
if (J <= high && heap[j] > Heap[i]) {
Swap (Heap[j], heap[i]);
i = j;
}
else {
Break
}
j = i
2;
}
}

void Createheap () {
for (int i = N/2; I >= 1; i--) {
Downajust (i, n);//Build Heap
}
}
void Heapsort () {
Because the final requirement is ascending, first build a big top heap; start with the non-leaf node.
Createheap ();
for (int i = n; i > 1; i--) {
Swap (Tempori[i], tempori);//With Heap top exchange
}
}
Count sort
The basic idea of counting sorting is to determine the number of elements in the sequence that have a value less than x for each element in the given input sequence (this is not a comparison of the size of each element, but a count of the value of the element and the summation of the count value). Once you have this information, you can store the x directly in the correct position of the final output sequence.

For example, we have three arrays of a, B, C;

A is the original array, the array to be sorted, the elements in the array are disorderly;

Then the C array as a secondary array, c[a[i]] "records how many elements are currently before the current is smaller than a[i], so that you can use the C array to the last sort of array B in the position of the elements, so b[c[a[i]] is a[i] in the final position after sorting. These are the basic ideas.

The counting sort is stable, the time complexity is about O (n+k);

Borrow auxiliary array c to get the sorted sequence B

The code is as follows:

Include <bits/stdc++.h>

using namespace Std;
const int MAXN = 10000;
int A[MAXN], B[MAXN], C[MAXN];
int n;
int main () {
CIN >> N;
for (int i = 0; i < n; i++) {
CIN >> A[i];
c[a[i]]++;
}
for (int i = 1; i < K; i++) {
C[i] + = c[i-1];
}
for (int i = n-1; I >= 0; i--) {
B[--c[a[i]] = a[i];
}
for (int i = 0; i < n; i++) {
cout << B[i] << "";
}
cout << Endl;
return 0;
}
In addition, you can make spatial optimizations for counting sorting:

The steps of the algorithm are as follows:
1. Find the largest and smallest elements in the array to be sorted
2. Count the number of occurrences of the element in the array for each value I, and deposit in the item I of array C
3. Accumulate all counts (starting with the first element in C, adding each item and the previous item)
4. Reverse-Populate the target array: Place each element I in the C (i) of the new array, subtract C (i) minus 1 for each element

Include <bits/stdc++.h>

using namespace Std;
const int MAXN = 10000;
const int INF = 0X3F3F3F3F;
int A[MAXN], B[MAXN], C[MAXN];
int n;
int main () {
CIN >> N;
int MIN = INF, MAX =-1;

``for (int i = 0; i < n; i++) {    cin >> a[i];    if (a[i] < MIN) { MIN = a[i]; }    if (a[i] > MAX) { MAX = a[i]; }}for (int i = 0; i < n; i++) {    c[a[i]-MIN]++;}//int k = MAX-MIN+1;k为C数组的大小int k = MAX-MIN+1for (int i = 1; i < k; i++) {    c[i] += c[i - 1];}for (int i = n-1; i >= 0; i--) {    b[--c[a[i]-MIN]] = a[i];}for (int i = 0; i < n; i++) {    cout << b[i] << " ";}cout << endl;return 0;``

}

Bucket sort
Bucket sequencing well understood, such as having a sequence a{3, 2, 9, 7, 5}

So we have a barrel C with a label of 0-10, and then we traverse a, and the record is c[a[i]]++;

And then according to the label from small to large output, if there are more than one element in the bucket, then output multiple times;

Include <bits/stdc++.h>

using namespace Std;
const int MAXN = 10000;
const int INF = 0X3F3F3F3F;
int A[MAXN], B[MAXN], C[MAXN];
int n;
int main () {
CIN >> N;
int MAX =-1;
for (int i = 0; i < n; i++) {
CIN >> A[i];
max = max (max, a[i]);
}
cout << MAX << Endl;
int C = MAX + 1;

``int c[C];memset(c, 0, sizeof(c));for (int i = 0; i < n; i++) {    c[a[i]]++;}for (int i = 0; i < C; i++) {    if (c[i] > 0) {        for (int j = 0; j < c[i]; j++) {            cout << i << " ";        }    }}return 0;``

}
Base sort
Time Complexity O (Nlog (r) m), abbreviation O (n*k)

The radix sort (radix sort) belongs to the "distributive sort" (distribution sort), also known as the "bucket method" (bucket sort) or bin sort, as the name implies, it is a part of the information through the key value, the elements to be sorted into some "barrels", In order to achieve the role of sequencing, the cardinal ranking method is a sort of stability, its time complexity is O (Nlog (r) m), where R is the base taken, and M is the number of heaps, at some point, the cardinality of the sorting method is more efficient than other stability ranking method. --Baidu Encyclopedia

There are two methods of implementation

Highest priority (most significant Digit first) method, referred to as MSD method: K1 Sorting group, the same group of records, the key code k1 equal, and then the group by the K2 sort into subgroups, after the key code to continue such a sorting group, Until the sub-groups are sorted by the most-important KD. By connecting the groups together, an ordered sequence is obtained.

The lowest bit first (Least significant Digit first) method, or LSD method, starts with the KD sequence, then sorts the kd-1, repeats it until the K1 is sorted, and then gets an ordered series.

Time efficiency : set to be sorted as N records, D key code, the value of the key code range is radix, then the time complexity of chain base sorting is O (d (N+radix)), where a trip allocation time complexity of O (n), a trip to collect time complexity O (radix), A total of D-trip allocations and collections. Space efficiency: You need to 2*radix a secondary space pointing to the queue and N pointers for static lists.

Include <bits/stdc++.h>

using namespace Std;
Const int MAXN = 10000;
Const int INF = 0X3F3F3F3F;
Int A[MAXN], B[MAXN], C[MAXN];
int n;
//The maximum number of digits for the data
int maxbit (int data[], int n) {
int d = 1;
int p = 10;
for (int i = 0, i < n; i++) {
while (Data[i] >= p) {
P *=;
++d;
}
}
return D;
}
void print (int a[], int n) {
for (int i = 0; i < n; i++) {
cout << a[i] << "";
}
cout << Endl;
}
void Radixsort (int a[], int n) {
int d = Maxbit (A, n);
int tmp[n];
Fill (tmp, tmp+n, 0);
//D-order
for (int i = 1; I <= D; i++) {
////per allocation before emptying the counter
Fill (c, c+10, 0);//Note that this is only open for ten

``    for (int j = 0; j < n; j++) {        int k = (a[j]/radix)%10;//统计桶        c[k]++;    }    for (int j = 1; j < 10; j++) {        c[j] += c[j - 1];    }    for (int j = n-1; j >= 0; j--) {        int k = (a[j]/radix)%10;        tmp[--c[k]] = a[j];    }    //收集数据到a数组    for (int j = 0; j < n; j++) {        a[j] = tmp[j];    }    radix *= 10;}print(a, n);``

}

int main () {
int n;
CIN >> N;
for (int i = 0; i < n; i++) {
CIN >> A[i];
}
return 0;
}

/**
9
5 9 3 12 7 6 4 2 0

**/

Bubble sort, quick sort, merge sort, insert sort, hill sort, heap sort, count sort, bucket sort, cardinal sort

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.