Several large sorting algorithms to understand

Source: Internet
Author: User

1. Inserting sorting algorithms

And we usually play a similar sort of poker, the left hand to pick up a card, do not need to compare, when the second card to pick up and before the card to compare, if less than the previous card I, and there is greater than the card i-1, I is the card to insert the position, card I and its future cards need to give it a place a[k+1] = After making a good position, insert it into the position of I.

Implementation algorithm:

 

voidInsertsort (intS[],intN) {        intI, j, K;  for(i =1; i<n;i++)        {            //find a suitable position (front to back) for A[i] in the order interval of the a[0...i-1]             for(j=i-1; j>=0; j--)                if(s[j]<S[i]) Break; //if we find a suitable location ,            if(J! = I1)            {                //move data that is larger than a[i] back                inttemp =S[i];  for(k = i1; k>j;k--) S[k+1] =S[k]; //put A[i] in the correct position at this time k = j, so s[j+1] = temp more convenient to understandS[k +1] =temp; }        }}

2. Quick Sort

Partition sorting idea, first select an element, divide all the elements into smaller (left) and larger than it (right) two parts, and then recursive to the left and right sides.

Algorithm implementation:

  

voidQuickSort (intS[],intLintR) {        if(L <r) {inti = l, j = r, x =S[l];  while(I <j) { while(I < J && S[j] >=x) J--; if(I <j) S[i++] =S[j];  while(I < J && S[i] <x) I++; if(I <j) S[j--] =S[i]; } S[i]=x; QuickSort (S, l, I-1); QuickSort (S, I+1, R); }};

Several large sorting algorithms to understand

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.