1 插入排序
void insertion_sort(int* array,int len){
int i,j,key;
for(j = 1; j < len; j++){
key = array[j];
i = j - 1;
while(i >= 0 && array[i] > key){
array[i + 1] = array[i];
i--;
}
array[i + 1] = key;
}
}
执行效率为: // ф( n^2)
2 合并排序:
void merge(int* array,int p,int q,int r){
int i = 0 ,j = 0,k = p;
int* buffer_low = new int[q - p + 1];
int* buffer_high = new int[r - q];
for(k = p; k <= q; k++){
buffer_low[k - p] = array[k];
}
for(k = q + 1; k <= r; k++){
buffer_high[k - q - 1] = array[k];
}
for(k = p; k <= r; k++){
if(j > r - q - 1){
array[k] = buffer_low[i];
i++;
}
else if(i > q - p){
array[k] = buffer_high[j];
j++;
}
else if(buffer_low[i] <= buffer_high[j]){
array[k] = buffer_low[i];
i++;
}
else{
array[k] = buffer_high[j];
j++;
}
}
delete buffer_high;
delete buffer_low;
}
void merge_sort(int* array,int p,int r){
if(p < r){
int q = (p + r) / 2;
merge_sort(array,p,q);
merge_sort(array,q + 1, r);
merge(array,p,q,r);
}
}
合并排序的执行效率是: //O(n lg n)
3 堆排序
#define LEFT_CHILD(i) ((i << 1) + 1)
#define RIGHT_CHILD(i) ((i << 1) + 2)
void max_heapify(int* array,int len,int index){
int l = LEFT_CHILD(index);
int r = RIGHT_CHILD(index);
int largest = 0;
if(l < len && array[l] > array[index]){
largest = l;
}else{
largest = index;
}
if(r < len && array[r] > array[largest]){
largest = r;
}
if(largest != index){
int tmp = array[index];
array[index] = array[largest];
array[largest] = tmp;
max_heapify(array,len,largest);
}
}
void build_max_heap(int* array,int len){
for(int i = len / 2 - 1 ; i >= 0; i--){
max_heapify(array,len,i);
}
}
void heap_sort(int* array,int len){
build_max_heap(array,len);
for(int i = len - 1; i >= 0; i--){
int tmp = array[0];
array[0] = array[i];
array[i] = tmp;
max_heapify(array,--len,0);
}
}
堆排序的执行效率是: // O(n lg n)
4 快速排序
int partion(int* array, int p, int r){
int sentry = array[r];
int i = p - 1; //
int tmp = 0;
for(int j = p; j <= r - 1;j++){
if(array[j] <= sentry){
i++;
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
tmp = array[r];
array[r] = array[i + 1];
array[i + 1] = tmp;
return i + 1;
}
void quick_sort(int* array, int p, int r){
if(p < r){
int q = partion(array,p,r);
quick_sort(array,p,q - 1);
quick_sort(array,q + 1, r);
}
}
快速排序执行效率:
最坏情况: ф( n^2)
一般情况: O(n lg n)