快排 随机分割
2016-04-28 00:14
302 查看
计算机算法设计与分析第四版[王]
#include<iostream> #include <stdlib.h> using namespace std; inline void swap(int &a, int &b) { int c = a; a = b; b = c; } //随机分割 int Random(int a, int b)//随机在a--b选择一个整数 { return a + rand() % (b - a + 1); } template<class type> int RandomizedPartition(type a[], int p, int r)//随机分割 { int i = Random(p, r);//在p--r中随机选择一个数 swap(a[i], a[p]); return Partition(a, p, r); } template<class type> int Partition(type a[], int p, int r)//以随机选的那个数作为分割起点,p此时是之前随机选的a[i]的位置; { int i = p, j = r + 1; type x = a[p]; while (true) { while (a[++i] < x&&i < r); //找到比标杆大的元素 while (a[--j] > x); // 找到比标杆小的元素 if (i >= j) break; swap(a[i], a[j]); } a[p] = a[j]; a[j] = x; return j;//返回结束后分割点所在的位置 } template<class type> void RandomizedQuickSort(type a[], int p, int r) { if (p < r) { int q = RandomizedPartition(a, p, r); RandomizedQuickSort(a, p, q - 1);//左半端排序 RandomizedQuickSort(a, q + 1, r);//右半段排序 } } int main() { int a[] = { 5,1,66,44,87,32,12,66,99,45,32,156,456 }; RandomizedQuickSort(a, 0, 12); for (int i = 0;i < 12;i++) { cout << a[i] << endl; } }
相关文章推荐
- 快速排序
- C#快速排序算法实例分析
- C++快速排序的分析与优化详解
- js实现数组冒泡排序、快速排序原理
- php简单实现快速排序的方法
- Java 快速排序(QuickSort)原理及实现代码
- 快速排序和分治排序介绍
- java 算法之快速排序实现代码
- Java实现快速排序算法(Quicktsort)
- Java中的数组排序方式(快速排序、冒泡排序、选择排序)
- 快速排序的原理及java代码实现
- C/C++实现快速排序的方法
- c语言实现冒泡排序、希尔排序等多种算法示例
- 深入单链表的快速排序详解
- C++实现八个常用的排序算法:插入排序、冒泡排序、选择排序、希尔排序等
- JavaScript实现快速排序的方法
- C#使用委托实现的快速排序算法实例
- C语言的冒泡排序和快速排序算法使用实例
- javascript与Python快速排序实例对比
- php实现快速排序的三种方法分享