1、冒泡排序
注意:外层循环表示的冒泡排序执行的最大趟数,内层循环不依赖外层循环,从后向前把小数往前冒泡,使用flag来减少循环的次数
void BubbleSort(vector<int>& data) { int length = data.size(),i,j; bool flag; if(length <= 1)return; for (i = 0;i < length-1;i++)//排序的趟数,总共n-1次 { flag = true; for (j = length-1;j > i;j--) { if(data[j-1] > data[j])//把小的从后向前冒泡 { swap(data[j-1],data[j]); flag = false; } } if(flag) return;//本次没有交换一个数据,所有数据都已经排序 } }
2、插入排序
void InsertSort(vector<int>& data) { int length = data.size(),i,j; if(length <= 1)return; for (i = 1;i < length;i++)//外层循环表示未排序的子数组的起始位置 { int tmp = data[i]; for(j = i;j > 0;--j) { if (data[j-1] < tmp)break;//找到要插入的位置,注意这里不是data[j-1] < data[j] else data[j] = data[j-1]; } data[j] = tmp; } }
3、快排
int partition(int* data,int left,int right) { int tmp = data[left]; while (left < right) { while(left < right && data[right] >= tmp) -- right; if(left < right)data[left++] = data[right]; while(left < right && data[left] <= tmp) ++ left; if(left < right)data[right--] = data[left]; } data[left] = tmp; return left; } void quickSort(int* data,int left,int right) { if(left < right) { int provit = partition(data,left,right); quickSort(data,left,provit-1); quickSort(data,provit+1,right); } } void quickSort(int* data,int length) { quickSort(data,0,length-1); }
4、堆排序
void adjustUpToDown(vector<int>& data,int start,int end)//从上到下调整大根堆 { int value = data[start]; int son; for(son = (start<<1)+1;son < end;son = (son<<1)+1)//每次判断孩子是否小于end,不是判断start < end { if(son + 1 < end && data[son] < data[son+1])son++; if(data[son] <= value)break; data[start] = data[son]; start = son; } data[start] = value; } void createMaxHeap(vector<int>& data)//创建大根堆 { int length = data.size(),i; for (i = (length>>1) - 1; i >= 0;--i) { adjustUpToDown(data,i,length); } } void headSort(vector<int>& data) { int length = data.size(),i; if(length <= 1)return; createMaxHeap(data); for (i = length-1;i >0;i--) { swap(data[0],data[i]); adjustUpToDown(data,0,i); } }
5、归并排序
6、链表的排序
7、位排序
void bitSort(vector<int>&data) { int length = data.size(),i; bitset<100> bit_map; bit_map.reset(); for (i = 0;i < length;i++) { bit_map[data[i]] = 1; } for(i = 0;i < 100;i++) { if(bit_map[i] == 1)cout << i << " "; } cout << endl; }
原文地址:http://blog.csdn.net/fangjian1204/article/details/38637325