插入排序 选择排序 冒泡排序 快速排序

来源:互联网 发布:pcb线路板设计软件 编辑:程序博客网 时间:2024/06/08 14:48

插入排序:

#include <iostream>using namespace std;void insertSort(int *a,int n){for(int i=0;i<n-1;++i){int cur = a[i+1];int j=i;while (j>=0){if (cur<a[j]){a[j+1] = a[j];--j;}elsebreak;}a[j+1] = cur;}}int main(){int a[] = {1,15,2,33,66,11,32,99};insertSort(a,8);for (int i=0;i<8;++i)cout<<a[i]<<" ";}

冒泡排序:


#include <iostream>using namespace std;void bubbleSort(int *a,int n){for (int i=0;i<n-1;++i){bool flag = true;for (int j=n-1;j>i;--j){if (a[j]<a[j-1]){int temp = a[j-1];a[j-1] = a[j];a[j] = temp;flag = false;}}if (flag)break;}}int main(){int a[] = {1,3,2,66,77,55,0,6,5,100};bubbleSort(a,10);for (int i=0;i<10;++i)cout<<a[i]<<" ";}

选择排序:


#include <iostream>using namespace std;void selectSort(int *a,int n){for (int i=0;i<n-1;++i){int lower = i;for (int j=i+1;j<n;++j){if (a[j]<a[lower])lower = j;}int temp = a[i];a[i] = a[lower];a[lower] = temp;}}int main(){int a[]={1,55,2,77,3,88,97,56,0,11};selectSort(a,10);for (int i=0;i<10;++i)cout<<a[i]<<" ";}

快速排序,两种方法:

#include <iostream>using namespace std;void quickSort1(int *a,int left,int right){if (left<right){int temp = a[left];int l = left,r = right;while (l<r){while (a[r]>temp && l<r)--r;a[l] = a[r];while (a[l]<temp && l<r)++l;a[r] = a[l];}a[l] = temp;quickSort1(a,left,l-1);quickSort1(a,l+1,right);}}int partition(int *a,int left,int right,int target){while (left<right){while ( left<right & a[++left]<target);while ( left<right && a[--right]>target);int temp = a[left];a[left] = a[right];a[right] = temp;}return left;}void quickSort2(int *a,int left,int right){if (left>=right)return;int pivotindex = (left+right)/2;int temp = a[right];a[right] = a[pivotindex];a[pivotindex] = temp;int p = partition(a,left-1,right,a[right]);temp = a[p];a[p] = a[right];a[right] = temp;quickSort2(a,left,p-1);quickSort2(a,p+1,right);}int main(){int a[]={5,7,3,8,1,22,66,12,32,15};quickSort2(a,0,9);for (int i=0;i<10;++i)cout<<a[i]<<" ";}




0 0