5 Class (8 kinds) common internal sorting algorithm (for C, C + +, Java)

Source: Internet
Author: User

/**

* 5 Class (8 kinds) common internal sorting algorithm (for C, C + +, Java)

*

* Internal Sort Category:

* 1) Insert sort (1. Direct insertion Sort, 2 hill sort)

* 2 Exchange sort (1. Bubble sort, 2 quick sort)

* 3) Select sort (1. Direct selection sort, 2. Heap sort)

* 4) Merge sort

* 5 allocation sort (cardinality sort)

*

* Author Wei Sama

*/


(1) Average time performance: the best way to quickly sort, but in the worst case than heap sorting and merge sort; When n is large, the merge sort is faster than the heap sort, but requires the most auxiliary space.

(2) Simple ordering is the simplest way to insert a sort directly, which is the best sorting method when the record is "basically ordered" or the n value is small. Therefore, it is often used in conjunction with other sorting methods.

(3) Cardinal order is most suitable for sequences with large n values and smaller keywords. If the keyword is also large, and most of the records in the sequence of the "highest bit keyword" are different, you can also press the "highest bit keyword" to separate the sequence into several sequences, and then use the direct insertion sort.

(4) From the stability point of view, Cardinal order is a stable sorting method, most of the time complexity of O (N2) Simple sorting method is stable. However, fast sorting, heap sequencing, and hill sorting are all unstable in the order of time performance.

The following is the implementation of the sorting algorithm, where the Exchange function is

void swap (int a[], int low, int high)

{

int temp = A[low];

A[low] = A[high];

A[high] = temp;

}

In addition to the cardinal order in Java to make a small change, other functions can be applied to C + +, Java (of course, Java can also reduce the number of parameters and thin code).

1.1 Direct Insertion Sort

(1) The basic idea: in order to sort of a group of numbers, assuming that the front (n-1) [n>=2] number has been sorted in order, now to the number of n inserted into the previous ordered number, so that the number of n is also ranked in good order. Repeat the loop until all the order is sorted.

(2) Example



void Insertsort (int a[], int n)

{

int i,j;

for (i = 1; i < n; i++)

{

for (j=i;j>0&&a[j]<a[j-1];j--)

Swap (A, J, j-1);

}

}


1.2 @@ 希尔 Sort (minimum increment sort)

(1) Basic idea: The algorithm first will be sorted by a group of numbers by an increment D (n/2,n to the number of sorted numbers) into several groups, the subscript that is recorded in each group differs D. Inserts a direct sort of all elements in each group, and then groups it with a smaller increment (D/2). Make a direct insert sort in each group. When the increment is reduced to 1 o'clock, the sort completes after a direct insert sort.

(2) Example:


void Shellsort (int a[], int n)

{

for (int gap = N/2; gap>=1; gap/= 2)//outermost loop responsible for determining step size

for (int i=gap; i<n; i++)//2 layer loop for direct insert ordering for each group

Inner Loop is a direct insert sort

for (int j = i; j>=0 && a[j]<a[j-gap]; J-= Gap)

Swap (A,J,J-GAP);

}

2.1 Bubble Sort

(1) The basic idea: in order to sort of a group of numbers, the current has not yet lined up in the range of the total number of adjacent two numbers from top to bottom to compare and adjust, so that the larger number to sink, smaller upward. That is, whenever two adjacent numbers are compared and found to be in reverse order, they are interchanged.

(2) Example:


void Bubblesort (int a[], int n)

{

for (int i=1;i<n;i++)//= maximum comparison n-1 times

for (int j=0;j<n-i;j++)//Sort from go after

if (a[j]>a[j+1])

Swap (a,j,j+1);

}

2.2 @@ 快速 Sort

(1) Basic idea: Select a datum element, usually select the first element or the last element, through a scan, the backlog sequence is divided into two parts, one is smaller than the datum element, and the other is greater than or equal to the datum element, when the datum element is in its correct position, And then recursively sort the two parts of the partition in the same way. Recursive end condition: l>=r.

(2) Example:


void QuickSort (int a[], int left, int right) {

int l=left;//Save Left

int r=right;//Save Right

Value of axis in int p=a[l];//

if (l>=r)//length not enough or recursive end flag

Return

while (L<r) {

The following first right and left order cannot be reversed. Because the default axis is L, if the change of the big bad.

while (A[r]>=p&&l<r) r--;//is swept from the back, smaller than the middle axis to the left of the middle axis

A[L]=A[R];

while (A[l]<=p&&l<r) l++;//from the back sweep, larger than the central axis to the right of the central axis

A[R]=A[L];

}

a[l]=p;//when the order is complete, the l=r place is vacant and the middle axis is placed there

Continue recursive call sorting

QuickSort (A,LEFT,L-1);/Central axis no longer participate in the next round of sorting

QuickSort (a,l+1,right);/Central axis no longer participate in the next round of sorting

}

3.1 Simple Selection sort

(1) Basic idea: In the number of groups to be sorted, select the smallest number and the number of the first position exchange, and then in the remaining number to find the smallest and the second position of the number of exchanges, so as to cycle to the penultimate and the last number of comparisons.

(2) Example:


void Selectsort (int a[], int n) {

for (int i=0;i<n-1;i++) {//n-1 trip sort

int l=i;//Default minimum value is I subscript element

for (int j=n-1;j>i;j--)//j traversal from back forward

if (A[j]<a[l])

l=j;//find a smaller value subscript than a[l]

Swap (A,I,L);

}

}

3.2 @@ 堆 sorting

(1) Basic idea: heap sort is a kind of tree-shape selection, which is an effective improvement to the direct selection sort.

The heap is defined as follows: A sequence with n elements (h1,h2,..., HN), which is called a heap only if it satisfies (hi>=h2i,hi>=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2). Only the heap that satisfies the former condition is discussed here. As you can see from the definition of the heap, the top element of the heap (that is, the first element) must be the maximum item (the large top heap). A complete binary tree can visually represent the structure of a heap. The top of the heap is the root and the other is Zuozi and right subtree. Initially, the sequence of numbers to be sorted is considered to be a sequential two-tree, which adjusts their storage order to make it a heap, at which point the number of root nodes of the heap is the largest. The root node is then exchanged with the last node of the heap. Then readjust the number of front (n-1) to make it a heap. And so on, until there are only two nodes in the heap, and exchange them, and finally get an ordered sequence of n nodes. From the description of the algorithm, heap sequencing requires two processes, one is to build a heap, and the other is to exchange positions between the top of the heap and the last element of the heap. So the heap sort has two function components. The first is to build the seepage function of the heap, and the second is to call the function of the infiltration function to realize the sort.

(2) Example:

Initial sequence: 46,79,56,38,40,84

Build heap:


Swap, kicking out the maximum number from the heap


Pile up the remaining nodes and swap the maximum number of kicks.


And so on: The last two remaining nodes in the heap are swapped, kicked out, sorted and finished.

/*

The following heap sorting algorithms include two functions: Heapadjust+heapsort

Heap sequencing is a recurring operation of the following two processes:

1, build heap;

2. Swap the top and bottom elements of the heap.

Until the last two remaining nodes in the heap are exchanged, kick out a, sorted finish.

*/

Set up a large pile of arrays from 0 to end

void Heapadjust (int a[], int end) {

for (int i= (end-1)/2;i>=0;i--) {//(END-1)/2 represents the last non-leaf node. Search the other root nodes forward.

int f=i;//f Save the node being judged

Compare the current node F's left and right children node, note the larger subscript Cmax, and then compare A[f] and A[cmax],

The large is exchanged as the parent node, and the smaller is the parent node of the next level and continues to compare.

while (f*2+1<=end) {//If the child node of the current K node exists

The index of the left child node of the int cmax=2*f+1;//f node, which defaults to this as the subscript for the larger child nodes.

if (cmax+1<=end) {//cmax+1 represents the right child of the K node, if the right child node exists

if (A[cmax]<a[cmax+1]) {//If the value of the right child node is greater

cmax++;//then the right child is Cmax.

}

}

if (A[f]<a[cmax]) {//If the value of the F node is less than Cmax nodes

Swap (A,f,cmax);

f=cmax;//to Cmax for the father to continue to compare

}else

break;//If f itself is the largest, there is no need to recycle.

}

}

}

Heap Sort

void heapsort (int a[],int n) {

for (int i=0;i<n-1;i++) {//Loop build heap, output heap top element. N-1 Trip Sort

Heapadjust (a,n-1-i);//The end element of the current heap is labeled N-1-i

Swap heap Top and last Element (A,0,n-1-i);

}

}

4 @@ 归并 Sort

(1) Basic sort: Merge (merge) sorting method is to combine two (or more than two) ordered table into a new ordered table, that is, to divide the sequence into several subsequence, each subsequence is ordered. Then the ordered Subsequence is merged into the whole ordered sequence.

(2) Example:


/*

The following merge sorting algorithms include two functions: Merge+mergesort

Divide the array into two halves and sort each side recursively until you have only two or one element left to stop the recursion.

The smaller of the elements on both sides of the original array is first copied to a cached array, which is copied back from small to large rows.

*/

Merging the two arrays that are already sorted

void merge (int a[],int c[], int l, int m, int r) {

int mid=m+1;//The start subscript of the right array

int i=l;//i The index of the record cache array

int ci=l;//the subscript used to copy the cached array to the original array

while (L<=M&&MID<=R)

Remove the smaller cache array from both sides of the array

if (A[l]<=a[mid])

C[i++]=a[l++];

Else

C[i++]=a[mid++];

At the end of the loop, there must be one side already completely moved to the cache array, but I don't know which side,

Just put the rest of the list in the cached array in sequence, because only one of the following loops executes

while (L<=M)

C[i++]=a[l++];

while (MID<=R)

C[i++]=a[mid++];

Copy the contents of the cached array back to the original array

while (CI<=R)

A[ci]=c[ci++];

}

Merge sort

void mergesort (int a[],int c[], int l, int r) {

if (l<r) {

int m= (L+R)/2;//Find Intermediate Index

MergeSort (a,c,l,m);//to the left array recursively

MergeSort (A,C,M+1,R)//to the right array for recursion

Merge (A,c,l,m,r);

}

}

5 @@ 基数 Order

(1) The basic idea: all the values to be compared (positive integer) unified to the same number of digits, the number of short digits before the number 0. Then, start at the lowest bit, and then sort it one at a time. This is done from the lowest bit to the highest order, and the sequence becomes an ordered series.

(2) Example:


/*

The following cardinality sorting algorithm includes two functions: Maxbit+radixsort

multiple keyword sorting. Take a 10-in integer as an example: Split the shape by every bit, and then compare each bit from low to high. It is divided into two main processes:

(1) Allocation, first from a single-digit start, according to the bit value (0-9), respectively put into the 0~9 bucket (such as 53, Single-digit 3, then put into the 3rd bucket)

(2) collection, and then put the data placed in the 0~9 bucket in order into the array

Repeat (1) (2) process, from single-digit to highest (e.g. 32-bit unsigned maximum number 4294967296, top 10 digits)

*/

To find the maximum number of digits in a data

int maxbit (int a[], int n) {

int d = 1;

int max=a[0];

for (int i = 0; i < n; i++) {

if (A[i]>max)

Max=a[i];

}

while (Max/10 > 0) {

d++;

Max/= 10;

}

return D;

}

Cardinality sort

void Radixsort (int a[], int n) {

int d = Maxbit (A, n);//maximum bit width, that is, number of keywords

int * temp = new int[n];//cache array. Java:int[] Temp=new Int[n];

int * Count = new int[10];//counter, also called bucket. Java:int[] Count=new int[10];

int I, j, K;

int bit = 1;//bit, i.e. Single-digit 1, 10 bit 10, hundred 100, etc.

for (i = 0; i < D; i++) {//D-Order

for (j = 0; J < N; j + +)

COUNT[J] = 0;//empty counter before each allocation

Allocation process

for (j = 0; J < N; j + +) {

K = (a[j]/bit)%10;//to find the current allocation bit of the current number, corresponding to the bucket subscript

count[k]++;//number of barrels recorded +1

}

for (j = 1; J < J + +)

count[j]=count[j-1]+count[j];//@@ 难点. COUNT[J] is the ordinal number of the last element in bucket J in Temp[n].

Note that the sequence number is not subscript. ordinal = Subscript +1, because the array element subscript starts at 0.

So in the following collection process count[j]-1 is the real subscript of the element.

Collection process. Collect the records in the bucket into temp. @@ 注意 must be collected in reverse order. Otherwise the result of the order is not stable.

for (j = n-1 J >= 0; j--) {

K = (a[j]/bit)%10;//find the barrel subscript of a[j]

count[k]--;//takes out an element from the bucket, the Count[k after 1 represents the subscript of the element being taken out of the TENP.

Temp[count[k]] = a[j];

}

Copy the contents of the temporary array into a

for (j = 0; J < N; j + +)

A[J] = Temp[j];

bit*=10;

}

Delete [] Temp;//java code should erase this line.

Delete [] Count;//java code should erase this line.

}

/* Test Results * *

int main () {

int i;

const int n=10;

int ia[]={9,8,7,6,5,4,3,2,1,0};

Insertsort (Ia,n);

for (i=0;i<n;i++)

cout<<ia[i]<< ",";

cout<<endl;

int ia2[]={9,8,7,6,5,4,3,2,1,0};

Shellsort (Ia2,n);

for (i=0;i<n;i++)

cout<<ia2[i]<< ",";

cout<<endl;

int ia3[]={9,8,7,6,5,4,3,2,1,0};

Bubblesort (Ia3,n);

for (i=0;i<n;i++)

cout<<ia3[i]<< ",";

cout<<endl;

int ia4[]={9,8,7,6,5,4,3,2,1,0};

QuickSort (ia4,0,n-1);

for (i=0;i<n;i++)

cout<<ia4[i]<< ",";

cout<<endl;

int ia5[]={9,8,7,6,5,4,3,2,1,0};

Selectsort (Ia5,n);

for (i=0;i<n;i++)

cout<<ia5[i]<< ",";

cout<<endl;

int ia6[]={9,8,7,6,5,4,3,2,1,0};

Heapsort (Ia6,n);

for (i=0;i<n;i++)

cout<<ia6[i]<< ",";

cout<<endl;

int ia7[]={9,8,7,

Related Article

Contact Us

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.