下面显示的是常用排序算法中的冒泡排序,选择排序,shell排序和插入排序以及快速排序这5种常见的排序算法的程序代码:下面的是string类的复制控制函数和各类重载函数的写法:(以后会陆续添加相关的函数重载) #include <iostream> using namespace std; void bubble_sort(int a[],int num) { int i,j; for(i=0;i<num-1;i++) //进行num-1次循环 { for(j=0;j<num-i-1;j++) { if(a[j]>a[j+1]) { int temp; temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } void select_sort(int a[],int num) { int i,j; for(i=0;i<num;i++) { for(j=i+1;j<num;j++) { if(a[i]>a[j]) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; } } } } void quick_sort(int a[],int s,int e) { int i,j; int x=a[s]; i=s; j=e; if(s<e) { while(i<j) { while(i<j && a[j]>= x) { j--; } if(i<j && a[j]< x) { int temp ; temp = a[j]; a[j] = a[i]; a[i] = temp; i++; } while(i<j && a[i]<=x) { i++; } if(i<j && a[i]>x) { int temp; temp = a[i]; a[i] = a[j]; a[j] = temp; j--; } } quick_sort(a,s,j-1); quick_sort(a,i+1,e); } } void shell_sort(int a[],int num) { int deep = num; while(deep >1) { deep=(deep+1)/2; for(int i=0;i<num-deep;i++) { if(a[i+deep] < a[i]) { int temp = a[i+deep]; a[i+deep] = a[i]; a[i] = temp; } } for(int i=0;i<8;i++) { cout<<a[i]<<" "; } cout<<endl; } } void insert_sort(int a[],int num) { int temp; for(int i=1;i<num;i++) { temp = a[i]; int compare = i; while(compare >0) { if(a[compare]<a[compare-1]) { int p=a[compare]; a[compare] = a[compare-1]; a[compare-1] = p; } else { temp =a[compare]; } compare--; } for(int i=0;i<num;i++) { cout<<a[i]<<" "; } cout<<endl; } } void print(int a[] , int num) { for(int i=0;i<num;i++) { cout<<a[i]<<" "; } cout<<endl; } void main() { int a[8]={49 , 38 , 21 , 13 , 52 ,7 ,55 ,49}; //bubble_sort(a,8); cout<<"冒泡排序的结果"<<endl; //print(a,8); //select_sort(a,8); cout<<"选择排序的结果"<<endl; //print(a,8); //quick_sort(a,0,7); cout<<"快速排序的结果"<<endl; //print(a,8); //shell_sort(a,8); cout<<"Shell排序的结果"<<endl; //insert_sort(a,8); print(a,8); }
常用的选择排序.Shell排序.快速排序.冒泡排序.插入排序的算法
最新推荐文章于 2021-05-14 22:23:22 发布