冒泡排序
1 #include <iostream>
2 #include<string>
3 #include<cstring>
4
5
6 using namespace std;
7 void bubbleSort(int array[],int n)
8 {
9 for(int i=0;i<n;i++)
10 {
11 for(int j=0;j<n-i-1;j++)
12 {
13 if(array[j]>array[j+1])
14 {
15 int temp =array[j];
16 array[j]=array[j+1];
17 array[j+1]=temp;
18 }
19 }
20 for(int k=0;k<n;k++) cout<<" "<<array[k];
21 cout<<endl;
22 }
23 }
24 int main()
25 {
26 int n;
27 cin>>n;
28 int a[1000];
29 for(int i=0;i<n;i++) cin>>a[i];
30 bubbleSort(a,n);
31 return 0;
32 }
快速排序
1 #include <iostream>
2
3 using namespace std;
4
5 void quickSort(int array[],int left,int right)
6 {
7 int ltemp=left,rtemp=right;
8 int f=array[(left+right)/2];
9 while(ltemp<rtemp)
10 {
11 while(array[ltemp]<f) ++ltemp;
12 while(array[rtemp]>f) --rtemp;
13 if(ltemp<=rtemp)
14 {
15 int t=array[ltemp];
16 array[ltemp]=array[rtemp];
17 array[rtemp]=t;
18 --rtemp;
19 ++ltemp;
20 }
21 }
22 if(ltemp==rtemp) ltemp++;
23 if(left<rtemp) quickSort(array,left,ltemp-1); //左半段排序
24 if(ltemp<right) quickSort(array,rtemp+1,right); //右半段排序
25 }
26 int main()
27 {
28 int n;
29 cin>>n;
30 int array[1000];
31 for(int i=0;i<n;i++) cin>>array[i];
32 //int array[] = { 4, 3, 2, 1, 9, 7, 5, 8, 6 };
33 //int size = sizeof(array) / sizeof(*array); //求数组长度
34 quickSort(array, 0, n - 1);
35 for (int i = 0; i < n; i++) cout << array[i] << " ";
36 return 0;
37 }
选择排序
1 #include <iostream>
2
3 using namespace std;
4
5 void selectSort(int array[],int n)
6 {
7 int index, temp;
8 for(int i=0;i<n;i++)
9 {
10 index=i;
11 for(int j=i+1;j<n;j++)
12 {
13 if(array[j]<array[index])
14 {
15 index=j;
16 }
17 }
18 temp=array[i];
19 array[i]=array[index];
20 array[index]=temp;
21 for(int k=0;k<n;k++) cout<<" "<<array[k]; //输出每一次排序
22 cout<<endl;
23 }
24 }
25
26 int main()
27 {
28 int n;
29 cin>>n;
30 int a[n];
31 for(int i=0;i<n;i++) cin>>a[i];
32 selectSort(a,n);
33 return 0;
34 }
插入排序
1 #include <iostream>
2
3 using namespace std;
4 void insertSort(int array[],int n)
5 {
6 for(int i=1;i<n;i++)
7 {
8 for(int j=i;j>0;j--)
9 {
10 if(array[j]<array[j-1])
11 {
12 int temp=array[j];
13 array[j]=array[j-1];
14 array[j-1]=temp;
15 }
16 }
17 for(int k=0;k<n;k++) cout<<array[k]<<" ";
18 cout<<endl;
19 }
20 }
21 int main()
22 {
23 int n;
24 cin>>n;
25 int array[n];
26 for(int i=0;i<n;i++) cin>>array[i];
27 insertSort(array,n);
28 return 0;
29 }