算法导论——快速排序(Quick-Sort)
2014-08-15 16:33
274 查看
///快速排序算法(Quick-Sort) /* 与归并排序一样,快速排序也使用了分治的思想, 它的步骤就是递归式的分别将每个元素放到它最终应该放置的位置. * 第一步: 分解 数组A[p...r]被划分为两个(可能为空)的子数组A[p...q-1]和A[q+1...r], 使得A[p..q-1]中的每一个元素都小于等于A[q],而A[q]小于等于A[q+1..r]中的每一个元素。 * 第二部: 解决 通过递归调用快速排序,对于子数组A[p..q-1]和A[q+1,,r]进行排序. * 第三部: 合并 因为子数组都是原址排序的,所以不需要合并操作: 数组A[p..r]已经有序. 时间复杂度: 最坏:O(n^2) 平均:O(nlg(n)) */
#include <cstdio> #include <time.h> #include <cstdlib> void Swap(int &a,int &b) { int c = a; a = b; b = c; } //交换函数
/* 1: Partition() 参数: 1待排序列的指针或者引用,2待排起始下标,3待排终止下标; 函数的作用有两个,一是数据进行原址排序, 二是返回以某一项最终在序列的下标(最终位置) 一般为起始项或者终止项. 时间复杂度: O(n) */ int Partition(int *a,int l,int r){ //划分函数 int temp = a[r]; int i = l - 1; int j = l; for(j = l; j < r; ++j){ if(a[j] < temp){ i = i + 1; Swap(a[i],a[j]); } } Swap(a[i + 1],a[r]); return i + 1; }
/* 2:Quick_Sort() 参数: 1待排序列的指针或者引用,2待排起始下标,3待排终止下标; 函数的作用是利用Partition()函数返回的划分下标值来递归的调用自身直至每个调用中(l < r). 时间复杂度: O(lg(n)) */ void Quick_Sort(int *a,int l,int r){ //快速排序函数 if(l < r){ int pos = Partition(a,l,r); Quick_Sort(a,l,pos-1); Quick_Sort(a,pos+1,r); } }
int main(){ int i,n; int *a; while(scanf("%d",&n)!=EOF){ a = new int[n+1]; srand(time(NULL)); for(i = 1; i <= n; ++i){ a[i] = 1 + rand()%1000; printf("%d ",a[i]); } printf("\n"); Quick_Sort(a,1,n); for(i = 1; i <= n; ++i){ printf("%d ",a[i]); } printf("\n"); } return 0; }
相关文章推荐
- 排序算法之快速排序(quick_sort)
- C标准库中的快速排序(quick-sort)函数 [简单应用]
- 算法导论(implementation of quick sort)
- 快速排序(quick_sort)
- Algorithm: quick sort implemented in python 算法导论 快速排序
- 排序_Quick_Sort(快速排序)
- quick_sort(快速排序)c语言实现
- 快速排序(quick-sort)
- 快速排序(Quick-Sort)
- 【数据结构笔记】快速排序(quick_sort)和快速选择(quick_select)--Python2.7
- 快速排序的简单实现(Quick_Sort)
- 快速排序(Quick_Sort)
- 快速排序的简单实现(Quick_Sort)
- 排序——快速排序(quick_sort)
- java quick sort(快速排序)
- 迭代的快速排序(Iterative Quick Sort)
- 快速排序(Quick-Sort)
- [LeetCode] 148. Sort List (Linked List) - Using Quick Sort(小改动)
- 数据排序谁最快(javascript中的Array.prototype.sort PK 快速排序)
- quick_sort