快速排序
来源:互联网 发布:超人 知乎 编辑:程序博客网 时间:2024/04/18 09:46
无聊练习下快排:
非递归版(从大到小):
#include <iostream>#include <cstdio>#include <ctime>#include <cstdlib>using namespace std;int Stack[1024],top;int solve(int *arr, int st, int ed){ int tem = arr[st]; while(st < ed) { while(st < ed && arr[ed] <= tem) ed --; arr[st] = arr[ed]; while(st < ed && arr[st] >= tem) st ++; arr[ed] = arr[st]; } arr[st] = tem; return st;}void QuickSort(int *arr, int st, int ed){ if(st < ed) { int mid = solve(arr,st,ed); if(st < mid-1) { Stack[++top] = st; Stack[++top] = ed; } if(mid+1 < ed) { Stack[++top] = mid+1; Stack[++top] = ed; } while(top) { int high = Stack[top--]; int low = Stack[top--]; mid = solve(arr,low,high); if(low < mid-1) { Stack[++top] = low; Stack[++top] = mid-1; } if(mid + 1 < high) { Stack[++top] = mid+1; Stack[++top] = high; } } }}int main(){ int *array; int len; while(cin >> len) { array = new int [len+1]; top = 0; srand((int)time(0)); for(int i=1; i<=len; i++) array[i] = rand()%1024 + 1; int startTime = clock(); QuickSort(array,1,len); int endTime = clock(); printf("Sort Time: %d\n",endTime-startTime); for(int i=1; i<=len; i++) printf("%d ",array[i]); puts(""); delete [] array; array = NULL; } return 0;}
递归版(从小到大):
void QuickSort(int *arr, int st, int ed){ if(st < ed) { int low = st, high = ed; int tem = arr[st]; while(low < high) { while(low < high && arr[high] >= tem) high --; arr[low] = arr[high]; while(low < high && arr[low] <= tem) low ++; arr[high] = arr[low]; } arr[low] = tem; QuickSort(arr,st,low-1); QuickSort(arr,low+1,ed); }}
- 快速排序
- 快速排序
- 快速排序
- 快速排序!
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- 快速排序
- Hibernate开发全面流程和开发配置
- centos 6.3下安装QQ2012
- Windows 8 乙肝自测隐私声明
- CentOS 6.2 下安装QQ2012完全可用
- boost使用简要指南
- 快速排序
- 关于java core的一些知识
- 基本垃圾回收算法
- 架构、框架、模式和平台
- #pragma comment lib
- Eclipse 自动提示功能配置
- ipcs简单介绍
- 常见排序算法的稳定性
- 谈30岁后it人员职业发展规划