Data structure and algorithm analysis-sorting

Source: Internet
Author: User

Xiabodan Source: Http://blog.csdn.net/xiabodan

Sorting Algorithms (sorting algorithm) is an integral part of computer algorithms. is also part of the program = algorithm + data structure (algorithm).

Experimental platform: Raspberry 2 B + Ubuntu Mate

Insert SortOuter circulation I from 1 to N-1, inner circulation by J from I to 1, each inner loop inserts a "J" into the correct position of the sequence a "0"-a "I", which guarantees that the sequence a "0"-a "I" is already ordered after each outer loop, but that the outer loop inserts itself between a "0"-a "I", And does not affect the original sequence correctness. As with the bubbling algorithm, the O (n^2) times are compared and exchanged, for example

Insert sort//stable//o (n^2) comparisons and Swaps//adaptive:o (N) time time nearly sorted//very low overheadvoid insertion (ele Menttype a[],int N) {int p = 0; int j = 0; for (p=1;p<n;p++) {ElementType tem = a[p]; for (j=p;j>0&&a[j-1]> tem;j--) {A[j] = a[j-1];} A[J] = tem;}}

Hill sortThe hill sort can sometimes become an incremental narrowing of the sort, selecting a range of size HK, inserting a sort of HK-separated elements, and gradually reducing the HK interval. Until HK becomes 1
Hill sort//o (N^3/2)   unstable//adaptive:o (N.LG (N)) time time nearly sorted//very low overheadvoid shell (ElementType a[ ],int n) {int i,j,inc;elementtype tem;for (inc=n/2;inc>0;inc/=2) {for (i=inc;i<n;i++) {tem = A[i];for (j=i;j>= Inc;j-=inc) {if (Tem<a[j-inc]) a[j] = A[j-inc];elsebreak;} A[J] = tem;}}}
Bubble sortBubble sort is more violent, outer loop i from a "0"-a "N-1", within the loop from a "N-1"-A "I", at the same time the cycle from the end of the loop has been to I close. and find out that the smallest element pops up to a "i+1", so called bubble sort. Very violent, but very stable, need 1+2+3+4+.......+n = N (n+1) = O (n^2) times comparison and exchange, the efficiency is very low. However, a "N-1"-A "I" is arranged according to the order of a time when the cyclic detection has not occurred in exchange. There's no need to sort. Therefore, it is assumed that the time complexity of the bubbling algorithm is only O (N) when the given data is nearly sorted.

Bubble sort//o (n^2)   stable//adaptive:o (N) time time nearly sorted//very low overheadvoid bubble (ElementType a[],int N) { int flag = 1;int I,j;for (i=0;i<n;i++) {flag = 0;for (j=n-1;j>i;j--) {if (A[j]<a[j-1]) {flag = 1;swap (a+j,a+j-1);}} if (flag = = 0) break;}}

Select sort

Select Sort, outer loop i from a "0"-a "N-1". Inner loop from a "i+1"-a "N-1". The inner loop is responsible for finding the element that is smaller than a "I" in a "i+1"-A "N-1", and using a K to mark its position, and to interchange a "I" with a "k" at the end of the inner loop. Then the element a "K" in a "i+1"-a "N-1" smaller than a "I" is placed in the position of a "I". That is, choose a minimum to put in a "I" this position.

The comparison of the selection order is O (n^2). But the number of exchanges is only O (N). Since the inner loop does not mark the smallest element at a time, it does not swap elements in real time.

Select Sort//not stable//o (1) Extra space//θ (n2) comparisons//θ (n) swaps//not adaptivevoid selection (ElementType a[],int N) { int I,j;int k;for (i=0;i<n;i++) {k = I;for (j=i+1;j<n;j++) {if (A[j]<a[k]) {k = j;}} Swap (A+I,A+K);}}


High-speed sequencingHigh-speed sequencing is a typical divide-and-conquer strategy that divides very large sets of a into very small modules. Processed individually. First you need to select a Hub element Pivot, and then divides the whole set of a into two halves, one for each element that is smaller than pivot, and set Al on the left. A group of elements that are larger than pivot are placed on the right. Called Set AR. Then the same method is recursive for the subsets of the left and right side, AL and AR respectively. Until the collection of Al and AR are only one element, in practice, generally do not let Al and AR are recursively recursive to 1 elements. One way to do this is when Al and AR are less than 10 ( Threshold Cut), it is not a fast-line algorithm. Instead, the insertion sorting algorithm is more efficient. Because this article is not conducive to the sorting of big data in the test. So just set the threshold cut to 10. See

Another problem is the choice of pivot element pivots, which has a very good selection of pivot elements . One commonly used is the three-digit median algorithm. That is, select the end of set A and the median element , and then select the median of these three numbers as pivot element pivots.


//high-speed sequencing//not stable//o (LG (n)) extra space (see discussion)//o (N2) time, but typically O (n LG (n)) Time//not adaptive#define CUT 3element Type MEDIAN3 (ElementType a[],int left, int right) {int center = (left +right)/2;if (A[left]>a[center]) swap (&a[left ],&a[center]), if (A[left]>a[right]) swap (&a[left],&a[right]), if (A[center]>a[right]) swap (&A [Center],&a[right]); swap (&a[center],&a[right-1]); return a[right-1];} void Qsort (ElementType A[],int left, int. right) {int. I,j;elementtype pivot;if (left + cut<= right) {pivot = MEDIAN3 (a,left , right); Select middle Element as Pivoti = Left;j = Right-1;for (;;) {while (A[++i]<pivot) {}while (A[--j]>pivot) {}if (i<j) swap (&a[i],&a[j]); elsebreak;} Swap (&a[i],&a[right-1]); Qsort (a,left,i-1); Qsort (a,i+1,right);} Elseinsertion (a+left,right-left+1);} void Quick1 (ElementType a[],int N) {Qsort (a,0,n-1);} 


Merge sortThe thought of merging and sorting is also the (Divide-and-conquer) divide-and-conquer strategy. The collection A is recursively divided. Until there is only one element left in the group, the combination starts at the beginning. The principle of composition is, for example, very image, not much explained. Many other things about merging algorithms can be seen in blog http://geeksquiz.com/merge-sort/

Merge sort//stable//(n) Extra space for arrays (as shown)//(LG (n)) extra space for linked lists//(n LG (n)) Time//not adaptive/ /does not require random access to datavoid Merge (ElementType a[],elementtype ta[],int lpos,int rpos,int rightend) {int lef tend = rpos-1;int Numelement = rightend-lpos + 1;int TPOs = lpos;while (lpos<=leftend && rpos<=rightend) if (A [Lpos] <= A[rpos]) ta[tpos++] = a[lpos++];elseta[tpos++] = a[rpos++];while (lpos<=leftend) TA[tpos++] = A[lpos++]; while (rpos<=rightend) ta[tpos++] = A[rpos++];int i = 0;for (i=0;i<numelement;i++,rightend--) {A[rightend] = TA[ Rightend];}} void Msort (ElementType a[],elementtype ta,int left,int right) {int center, if (left < right) {center = (left+right)/2; Msort (A,ta,left,center); Msort (A,ta,center+1;right); Merge (A,ta,left,center+1,right);}} void MergeSort (ElementType a[],int N) {ElementType *ta;ta = (elementtype*) malloc (sizeof (ElementType));//just malloc Once if (NULL! = TA) {msort (a,ta,0,n-1); free (TA);} elseprintf ("Error:ta CAN ' t be empty!\n ");} 



The header file includes a different variable and a print, swap function
typedef   int ElementType; #define N 10

Other function used for debugvoid print (ElementType a[],int n)  {int i = 0;printf (' after sorting\n '); for (i=0;i<n; i++) {printf ("%d \ n", A[i]);}}
void swap (ElementType *a,elementtype *b) {ElementType tem = *a;*a= *b;*b= tem;}



To be continued .....


Summary: a stable sort: Insert Sort. Bubble sort, Merge sort time complexity:O (n 2) o (n2) O (n lg (N) )
Unstable sort: Select Sort, Hill sort, heap row. Time complexity of the quick schedule:O (n2) O ( n3/2) o (n LG (n)) O (n LG (n ))

Bubbling and inserting is to slowly find the largest or smallest put on the first go; Select directly to find the largest or least placed to the first one. Merge, the quick row all uses the Devide-merge-conquer (divide the rule strategy), during still will use the above mentioned several main algorithms; the heap sort uses the idea of choosing sort. The bucket sort uses the method of space changing time; original aim.

References:

data structure and algorithm analysis- C Descriptive Narrative [M], mechanical industry press

Blog Park Vamei's blog: http://www.cnblogs.com/vamei/archive/2013/03/12/2948847.html

Tianjin City College A fine course: http://sjjp.tjuci.edu.cn/sjjg/datastructure/ds/web/paixu/paixu8.1.1.1.htm

A sort of foreign site has animation, analysis, for code: http://www.sorting-algorithms.com/

a domestic not too well-known foreign sites, inside the content seems to be more than algorithms:
Programming problems and Competitions:: Hackerrank
a Russian ACM contest site, there are algorithmic tournaments on an irregular basis:
Codeforces
It is said that a TOP2 university for the background of the algorithm site, relatively simple, and has been regularly updated algorithm novice tutorial, there are regular competitions:
Hihocoder
HDU hosted the ACM Algorithm contest site. There are regular competitions:
Welcome to Bestcoder
Cosmic level:
Uoj-universal Online Judge

PKU:/ httppoj.org/
Hangzhou Electric:/ httpacm.hdu.edu.cn/
Huazhong University:/ httpacm.hust.edu.cn/vjudge/toindex.action

Data structure and algorithm analysis-sorting

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.