#include<iostream>usingnamespace std;intmain(){int n;
cin >> n;int* p =newint[n];int t;for(int i =0; i < n;++i){
cin >> p[i];}for(int i =0; i < n;++i){for(int j =0; j < n - i -1;++j){//注意一下j=0if(p[j]> p[j +1]){swap(p[j], p[j +1]);}}}for(int i =0; i < n;++i){
cout << p[i]<<" ";}
cout << endl;}
选择排序
#include<iostream>#include<algorithm>usingnamespace std;intmain(){int n;
cin >> n;int* arr =newint[n];for(int i =0; i < n;++i){
cin >> arr[i];}for(int i =0; i < n;++i){int min = arr[i];int index = i;for(int j = i; j < n;++j){if(arr[j]< min){
min = arr[j];
index = j;}}swap(arr[i], arr[index]);}for(int i =0; i < n;++i){
cout << arr[i]<<" ";}
cout << endl;}
插入排序
#include<iostream>#include<algorithm>usingnamespace std;intmain(void){int n,j =0;
cin >> n;int* arr =newint[n];for(int i =0; i < n;++i){
cin >> arr[i];}for(int i =1; i < n;++i){for(int j = i -1; j >=0&&arr[j]>arr[j+1]; j--){swap(arr[j], arr[j +1]);}}for(int i =0; i < n;++i){
cout << arr[i]<<" ";}
cout << endl;return0;}
希尔排序
#include<iostream>#include<algorithm>usingnamespace std;intmain(void){int n, j =0;int i =0;
cin >> n;int* arr =newint[n];for(int i =0; i < n;++i){
cin >> arr[i];}int increasment = n;do{//确定分组的增量(就是间隔几个取一次数)
increasment = increasment /3+1;//每次分组有几个组就循环几次for( i =0; i < increasment; i++){//这里就到了大伙都熟悉的插入排序部分(i+increasment)的含义为比如就是第一组隔3个1 4 7 然后第二组就是2 5 8这样for(j = i + increasment; j < n; j += increasment){for(int k = j - increasment; k >=0&& arr[k]> arr[k + increasment]; k -= increasment){swap(arr[k], arr[k + increasment]);}}}}while(increasment>1);for(int i =0; i < n;++i){
cout << arr[i]<<" ";}
cout << endl;return0;}
快排
#include<iostream>#include<algorithm>usingnamespace std;voidQuickSort(int left,int right,int arr[]){//递归终止条件if(left > right){return;}int i, j;
i = left;
j = right;int t = arr[left];while(i < j){while(arr[j]>= t && i < j)--j;while(arr[i]<= t && i < j)++i;if(i < j){swap(arr[i], arr[j]);}}//把找到的值和一开始的基值进行交换
arr[left]= arr[i];
arr[i]= t;//递归调用QuickSort(left, i -1, arr);//每次right的值改变QuickSort(i+1, right, arr);//每次left的值改变}intmain(){int n, j =0;int i =0;
cin >> n;int* arr =newint[n];for(int i =0; i < n;++i){
cin >> arr[i];}QuickSort(0, n -1, arr);for(int i =0; i < n;++i){
cout << arr[i]<<" ";}
cout << endl;}