输入文件: in.txt
10
49 38 65 97 76 13 27 49 69 41
1、选择排序
2、冒泡排序
3、桶排序
4、插入排序
5、快速排序
1 //从小到大排序
2 #include <iostream>
3 const int N=1e2+10;
4 using namespace std;
5 int n,a[N];
6
7 void print(){
8 for(int i=1;i<=n;i++) cout<<a[i]<<" ";cout<<endl;
9 }
10
11 void qsort(int l,int r){
12 int i,j,midV;
13 i=l;j=r;
14 midV=a[(l+r)/2];
15 do{
16 while(a[i]<midV) i++;
17 while(a[j]>midV) j--;
18 cout<<midV<<" "<<i<<" "<<j<<endl;
19 if(i<=j){
20 int tmp=a[i];a[i]=a[j];a[j]=tmp;
21 i++;j--;
22 }
23 print();
24 }while(i<=j);
25 cout<<"左:"<<l<<" "<<j<<endl;
26 if(l<j) qsort(l,j);
27 cout<<"右: "<<i<<" "<<r<<endl;
28 if(i<r) qsort(i,r);
29 }
30
31 int main(){
32 freopen("in.txt","r",stdin);
33 freopen("quickSort.txt","w",stdout);
34 cin>>n;
35 for(int i=1;i<=n;i++) cin>>a[i];
36 print();
37 //核心代码
38 qsort(1,n);
39 //核心代码结束
40 print();
41 return 0;
42 }
快速排序的运行过程:
49 38 65 97 76 13 27 49 69 41
76 4 10
49 38 65 41 76 13 27 49 69 97
76 5 9
49 38 65 41 69 13 27 49 76 97
76 9 8
49 38 65 41 69 13 27 49 76 97
左:1 8
41 1 7
27 38 65 41 69 13 49 49 76 97
41 3 6
27 38 13 41 69 65 49 49 76 97
41 4 4
27 38 13 41 69 65 49 49 76 97
左:1 3
38 2 3
27 13 38 41 69 65 49 49 76 97
左:1 2
27 1 2
13 27 38 41 69 65 49 49 76 97
左:1 1
右: 2 2
右: 3 3
右: 5 8
65 5 8
13 27 38 41 49 65 49 69 76 97
65 6 7
13 27 38 41 49 49 65 69 76 97
左:5 6
49 5 6
13 27 38 41 49 49 65 69 76 97
左:5 5
右: 6 6
右: 7 8
65 7 7
13 27 38 41 49 49 65 69 76 97
左:7 6
右: 8 8
右: 9 10
76 9 9
13 27 38 41 49 49 65 69 76 97
左:9 8
右: 10 10
13 27 38 41 49 49 65 69 76 97
来看另外一组数据:
并不是midV的左边都比midV小,而是l->j比midV小,i->r比midV大
6、归并排序
1 //从小到大排序
2 //不给图了,图和线段树的图很像
3 #include <iostream>
4 const int N=1e2+10;
5 using namespace std;
6 int n,a[N],r[N];
7
8 //将有序表a[s->m]和a[m+1->t]合并
9 int merge(int s,int m,int t){
10 int i=s,j=m+1;//两个有序表的头
11 int k=s;
12 while(i<=m&&j<=t){
13 if(a[i]<=a[j]) r[k++]=a[i++];
14 else r[k++]=a[j++];
15 }
16 while(i<=m) r[k++]=a[i++];
17 while(j<=t) r[k++]=a[j++];
18 for(int i1=s;i1<=t;i1++) a[i1]=r[i1];
19 }
20 //将无序表a[s->t]排序
21 void mergeSort(int s,int t){
22 //拆
23 if(s==t) return ;
24 int mid=(s+t)/2;
25 cout<<"左: "<<s<<" "<<mid<<endl;
26 mergeSort(s,mid);
27 cout<<"右: "<<mid+1<<" "<<t<<endl;
28 mergeSort(mid+1,t);
29 //合
30 merge(s,mid,t);
31 }
32
33 int main(){
34 freopen("in.txt","r",stdin);
35 cin>>n;
36 for(int i=1;i<=n;i++) cin>>a[i];
37 //核心代码
38 mergeSort(1,n);
39 //核心代码结束
40 for(int i=1;i<=n;i++) cout<<a[i]<<" ";cout<<endl;
41 return 0;
42 }
归并排序排序过程:
说明一点:图和线段树的图很像,也是一般的DFS的访问顺序,这里是二叉树。
7、堆排序(二叉树排序)