标签:
关于排序算法的性能和稳定性总结,维基百科中文词条排序算法的总结很全面。
本文统一将数组从小到大排序。
1.插入排序
(1)直接插入排序,基本操作是将一个记录插入到已经排好序的的有序表中,从而得到一个新的,记录数曾1的有序表。
void InsertSort(int a [], int size){
int i,j,temp;
for(i = 1; i < size; i++){
temp = a[i]
if(j = i-1; temp < a[j] && j >=0; j--){
a[j+1] = a[j];
}
a[j] = temp;
}
}
(2)折半插入排序
(3)希尔排序
2.交换排序
(1)冒泡排序
(2)快速排序。快速排序是冒泡排序的一种改进。它的基本思想是,通过一趟排序将排序记录分割成独立的两部分,其中一部分的关键字均比另一部分的关键字小,中间的枢轴点移动到它最后的位置。然后分别对左右两部分的记录继续排序,以达到整个序列有序。
void QuidSort(int a[], int size){
Qsort(a, 0 ,size-1);
}
void Qsort(int a[], int low, int hight){
int pivotloc
if(low < high){
pivotloc = Partition(a, low, high);
Qsort(a, low, pivotloc - 1);
Qsort(a, pivotloc + 1, high);
}
}
int Partition(int a[], int low, int high){
int pivotkey = a[low];
while(low < high){
while( low < high && a[high] >= pivotkey) --high;
a[low]= a[high];
while(low < high && a[low] <= pivotkey) ++low;
a[high] = a[low];
}
a[low] = pivotkey;
return low;
}
3.选择排序
(1)简单选择排序
(2)堆排序
/*
* File: main.cpp
* Author: brownwn
*
* Created on 2015年1月14日, 下午3:07
*/
#include <cstdlib>
#include <stdio.h>
void HeapAdjust(int a[], int s, int m){
int rc = a[s];
int j;
for(j=2*s;j<=m;j*=2){
if(j<m && a[j] < a[j+1]) ++j;
if(rc >= a[j]) break;
a[s] = a[j];
s = j;
}
a[s] = rc;
}
//int a[] 1-length,a[0] not use
void heapSort(int a[], int length){
int i;
for( i = length/2; i>0; --i){
HeapAdjust(a,i,length);
} //此时a[1]最大
for(i = length; i > 1; --i){ //调整为大顶堆
int temp = a[1];
a[1] = a[i];
a[i] = temp;
HeapAdjust(a,1,i-1);
}
// return a[1]; 可以返回第一个值,最大值。
}
int main(int argc, char** argv) {
int a[7] = {0,1,5,8,10,6,20}; //注意这个数组,给索引1-7排序,所以长度为6。索引0的元素是没有用的。
heapSort(a, 6);
for (int i = 1; i <= 6; i++){
printf("%d\n", a[i]);
}
return 0;
}
4.归并排序
5.计数排序
标签:
原文地址:http://www.cnblogs.com/zhutianpeng/p/4222532.html