
#include <iostream> using namespace std; //快速排序,在子函数中,数组已被改变 void quick_sort(int *a, int left, int right) //left和right为索引值 { int temp; //存储每次选定的基准数(从最左侧选基准数) int t; int initial=left; int end=right; temp=a[left]; //***必须有这一部分***// if (left>right) //因为在递归过程中有减1加1的情况,当其越界时,直接return,不返回任何值,即结束当前程序块 return; while(left!=right) //此时左右index在移动中,若left==right,则跳出循环,将基数归位 { while(a[right]>=temp && left<right) //直到找到小于基准数的值为准 right--; while(a[left]<=temp && left<right) left++; if(left<right) //交换左右两侧值,当left=right时,跳出外层while循环 { t=a[right]; a[right]=a[left]; a[left]=t; } } a[left]=temp; //基数归位 //递归处理归位后的基准数的左右两侧 quick_sort(a,initial,left-1); //此时left=right quick_sort(a,left+1,end); }
颜色之间是对应关系,明白的一看就懂了。
void InsertSort(int arr[],int n){ for (int i =1;i <= n;++i){ for(int j = i;j > 0;--j){ if(arr[j] < arr[j -1]){ int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; }}}}
冒泡排序:
void BubbleSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; }}}}
最后,当然排序最省力的就是C++中的自定义排序了,直接用algorithm中的sort即可。
#include <algorithm>
bool cmp(int a,int b){
return a>b;
}
sort(a,a+n); //a为数组,n为数组的长度,默认是从小到大排序
sort(a,a+n,cmp);//cmp即为自定义比较函数,此处是从大到小排序。大顶堆实现:
来看一下实现
//堆排序
void HeapSort(int arr[],int len){
int i;
//初始化堆,从最后一个父节点开始
for(i = len/2 - 1; i >= 0; --i){
Heapify(arr,i,len);
}
//从堆中的取出最大的元素再调整堆
for(i = len - 1;i > 0;--i){
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
//调整成堆
Heapify(arr,0,i);
}
}再看 调整成堆的函数
void Heapify(int arr[], int first, int end){
int father = first;
int son = father * 2 + 1;
while(son < end){
if(son + 1 < end && arr[son] < arr[son+1]) ++son;
//如果父节点大于子节点则表示调整完毕
if(arr[father] > arr[son]) break;
else {
//不然就交换父节点和子节点的元素
int temp = arr[father];
arr[father] = arr[son];
arr[son] = temp;
//父和子节点变成下一个要比较的位置
father = son;
son = 2 * father + 1;
}
}
}堆排序的时间复杂度最好到最坏都是O(nlogn),较多元素的时候效率比较高