菜小弟的修仙路。
插入排序
/** * 直接插入排序算法,原理如同抓扑克 * */ #include <iostream> using namespace std; int main(){ int array[5] = {5,4,2,7,1}; for(int i=1;i<5;i++){ int temp = array[i]; int j=i-1; for(;(j>=0)&&(array[j]>temp);j--){ array[j+1] = array[j]; } array[j+1] = temp; } for(int i=0;i<5;i++){ cout<<array[i]<<" "; } system("pause"); return 0; }
归并排序
/** * 归并排序,分治算法,即把两个已排序的数组合并为一个数组 * 有一个小注意点,把两个有序数组归并时,在两个数组的末尾添加一个“无穷大”的元素,作为哨兵,这样就不用每次都判断是否有一个数组归并结束了 * */ #include<iostream> #define MaxN 100; using namespace std; void merge(int *a,int p,int q,int r){ int n1 = q-p+1; int n2 = r-p; int L[n1+1]; int R[n2+1]; for(int n=0;n<n1;n++){ L[n] = a[p+n]; } for(int n=0;n<n2;n++){ R[n] = a[q+n+1]; } L[n1] = MaxN; R[n2] = MaxN; int i=0;int j=0; for(int n=p;n<=r;n++){ if(L[i]<=R[j]){ a[n] = L[i]; i++; }else{ a[n] = R[j]; j++; } } } void Sort(int *a,int s,int e){ if(s==e){ return; } Sort(a,s,(s+e)/2); Sort(a,(s+e)/2+1,e); merge(a,s,(s+e)/2,e); } int main(){ int array[5] = {5,4,2,7,1}; Sort(array,0,4); //merge(array,0,2,4); for(int i=0;i<5;i++){ cout<<array[i]<<" "; } cout<<endl; system("pause"); return 0; }