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