Implementation and summary of various sorting algorithms

Source: Internet
Author: User

This paper mainly compares the performance of various sorts (average time complexity and worst case) and the basic implementation.
This default is arranged from small to large, the input data can be repeated, assuming that the input array is a, subscript from 0 to N-1

Note that when comparing the complexity of the algorithm, we will pay attention to the comparison of the key values and the number of exchanges.

1. Bubble sort
Bubble sort if not because the name is better remembered, there is no advantage. The idea is to make a trip over and over again the array (or the list can also be) adjacent to the two elements, if the previous one is larger than the next, then the Exchange. Thus, after each round, the largest element is "sunk" to the end of the array.

void Bubble_Sort(intint N){    for(int0; i<=N-2; i ++)        for(int0; i<=N-2-i; j++)            if(A[j]>A[j+1])                swap(A+j,A+j+1);}

It can be found that in the average and worst case, the key values are compared and the number of exchanges is O (n^2)

In the best case, the comparison of the key value is O (n^2), but the code is optimized after the key value of the exchange number O (n)

 Public void Bubblesort(intArr[]) {BooleanDidswap; for(inti =0, Len = arr.length; I < Len-1; i++) {Didswap =false; for(intj =0; J < Len-i-1; J + +) {if(Arr[j +1] < Arr[j]) {swap (arr, J, J +1); Didswap =true; }        }if(Didswap = =false)return; }    }

See http://www.cnblogs.com/melon-h/archive/2012/09/20/2694941.html

At the same time, bubble sort is still a stable algorithm.

2. Insert Sort
The idea of inserting a sort is for a a[i], we assume that it's all sorted before, the key is to look forward to a[i] position, j=i-1~0, compare a[i] and a[j], if A[J] big, then a[j] move backwards until a[j] hours, that's where a[i] is.

void Insertion_Sort(intint N){    int tmp,i,j;    for1; i<N; i++){        tmp = A[i];        //比较i之前的元素和A[i]的大小        for(j = i; j!=0&&A[j-1]>tmp; j--)            A[j] = A[j-1];  //移出空位        A[j] = tmp;    }}

The insertion sort is an improvement to the bubbling sort and is also a stable algorithm.
The worst case scenario is that the time complexity is O (n^2) in reverse order (from large to small)

3. Hill sort
Sort by D interval, in order to eliminate more than one reverse pair at a time.
D=2^k-1 (Better D)

void Shell_Sort(intint N){    int tmp,i,j;    for(int D = N/2; D>0; D/=2){//shell增量        for(i = D; i<N; i++){   //插入排序            tmp = A[i];            //比较i之前的元素和A[i]的大小            for(j = i; j!=0&&A[j-D]>tmp; j-=D)                A[j] = A[j-D];  //移出空位            A[j] = tmp;        }    }}

4. Select sort
For the current subscript position I, we want to find the smallest subscript min_i in i+1 to N-1 and the element exchange of I position

void Selection_Sort(intint N){    int i,j,min_i;    for0; i <N-1; i++){        min_i = i;        //找最小元交换        for(j = i+1; j<N; j++)            if(A[j]<A[min_i])   min_i =j;        swap(A+j,A+min_i);    }}

5. Heap Sequencing
First, build a maximum heap, so that the first element of the largest heap is the largest element, swapping it with the last element of the heap, and then resizing the heap to the maximum heap again, repeating the operation.

There are two ways to consider the building of a heap first
Method 1: Insert n elements one by one into an initially empty heap through the insert operation, O (NLGN)
In this way, the heap sort operation is always deletemin, saving the smallest elements.

void Heap_Sort(intint N){    BuilDHeap(A);   //O(N)    for0; i<N; i++)        TmpA[i]=DeleteMin(A);   //O(log(N))    for(i =0; i<N; i++)     //O(N)        A[i]=TmpA[i];}

The problem above is to use an extra array to store it.

Another sort of a heap,

#define LEFTCHILD (i) (2*(i) +1)//heap with 0 as the starting pointvoid Percdown (intA[],intIintN) {//From I to the left and right son filter, built with I as the root of the largest heap    intChildParent;inttmp TMP = A[i];//Find the location where TMP needs to be put     for(Parent= i;Parent * *<=n-1;Parent= child) {child = Leftchild (i);if(child!=n-1&&a[child]<a[child+1])//Right son largerchild++;if(Tmp>a[child]) Break;Elsea[Parent]=a[child]; } a[Parent]=tmp; }void Heap_sort (intA[],intN) {intI for(i=n/2; i>=0; i--)//build HeapPercdown (A,i,n); for(i=n-1; I>0; i--) {Swap (&a[0],&a[i]);//deletemaxPercdown (A,0, i); }}

Advantage, heap sorting is a sort of in-place method, suitable for the situation where the data volume is very large.

6. Quick Sort
In the case of data volume, it is the best-performing sorting method. The main idea is divide and conquer, it itself has a lot of trick,stl in the sort is the use of fast sorting, its source code is also worth a good study. Here are the main trick

1, the main element pivot selection, first use a median3 function, select the left (0), right (N-1), center three positions on the median, and place the median in right-1 position. (So long as consider a[left+1,right-2] The fact that the choice of the main element has a greater impact on performance, this method is better.
2, I start from left, J moves from Right-1 until the two intersect
3, stop, Exchange A[i] and a[right-1], recursive left and right two sub-sequences
4, when the length of the sequence is less than the threshold value, not recursion and use to insert the sort, which can also significantly increase the speed

Swap numbers void swap (int *a, int *b) {int tmp;TMP = *a;*a= *b;*B = tmp;}//choose The median of left, center andright int median3 (int *A, int left, int right) {int center = (left+right)/2;     if(A[left]>A[Center]) SwapA+left,A+center);     if(A[left]>A[Right]) SwapA+left,A+right);     if(A[center]>A[Right]) SwapA+center,A+right);Put median in right-1SwapA+center,A+right-1);    return A[right-1];}//insertion Sort---for small size array andIndex array void insertion_sort (int *A, int N) {int P; int i; int tmp;for (P =1; p < N; ++p) {TMP =A[P];for (i = P; i!=0&&a[i-1]>tmp;-I.)                A[i]=A[I1];         A[I] = tmp;}} void Quicksort (int *A, int left, int right) {if(right-left>Ten) {int pivot = MEDIAN3 (A, left, right);int i = Left; int j = right-1;For;;) {             while(A[++i]<pivot) {} while(A[--j]>pivot) {}if(i<j) Swap (A+i,A+J);            Else                 Break;} swap (A+i,A+right-1);Quicksort (A, index_a,left,i-1);Quicksort (A, index_a,i+1, right);}ElseInsertion_sort (A+left,right-left+1);}

The specific performance comparison can be referred to http://blog.sina.com.cn/s/blog_77795cad01011txt.html

7, bit sort
There's also a way to deal with big data, see a previous article
Massive data processing

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Implementation and summary of various sorting algorithms

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.