Introduction to Algorithms Chapter II

Source: Internet
Author: User

Insert Sort Source:

1#include <iostream>2#include <cstdio>3 4 using namespacestd;5 6 voidInsert_sort (inta[])7 {8      for(intj=1;j<Ten; j + +)9     {Ten         intkey=A[j]; One         inti=j-1; A          while(i>=0&& a[i]>key) -         { -a[i+1]=A[i]; thei--; -         } -a[i+1]=key; -     } + } -  + intMain () A { at     inta[Ten]; -     inti; -      for(i=0;i<Ten; i++) -scanf"%d",&a[i]); - Insert_sort (a); -      for(i=0;i<Ten; i++) inprintf"%3d", A[i]); -Puts""); to     return 0; +}
View Code

Reverse output:

1#include <iostream>2#include <cstdio>3 4 using namespacestd;5 6 voidInsert_sort (inta[])7 {8      for(intj=1;j<Ten; j + +)9     {Ten         intkey=A[j]; One         inti=j-1; A          while(i>=0&& a[i]<key) -         { -a[i+1]=A[i]; thei--; -         } -a[i+1]=key; -     } + } -  + intMain () A { at     inta[Ten]; -     inti; -      for(i=0;i<Ten; i++) -scanf"%d",&a[i]); - Insert_sort (a); -      for(i=0;i<Ten; i++) inprintf"%3d", A[i]); -Puts""); to     return 0; +}
View Code

Divide and conquer method: merge Sort

For two stacks of well-ordered, lowest-level running logic:

1#include <iostream>2#include <cstdio>3 #defineINF 1e94 using namespacestd;5 6 voidMerge_sort (intA[],intPintQintR)7 {8     intn1=q-p+1;9     intn2=r-Q;Ten     inti,j; One     intl[n1+1],r[n2+1]; A      for(i=0; i<n1;i++) -l[i]=a[p+i]; -      for(i=0; i<n2;i++) ther[i]=a[q+i+1]; -      -L[n1]=inf; r[n2]=inf; -I=0; j=0; +      for(intk=p;k<=r;k++) -     { +         if(l[i]<=R[j]) A         { ata[k]=L[i]; -i++; -         } -         Else -         { -a[k]=R[j]; inJ + +; -         } to     } + } -  the  * intMain () $ {Panax Notoginseng     inti; -     inta[Ten]; the      for(i=0;i<Ten; i++) +scanf"%d",&a[i]); AMerge_sort (A,0,4,9); the      for(i=0;i<Ten; i++) +printf"%3d", A[i]); -Puts""); $     return 0; $}
View Code

Introduction to Algorithms Chapter II

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.