快速排序C++版
2015-05-06 09:59
204 查看
// // main.cpp // QuickSort // // Created by 陈亚东 on 15/3/10. // Copyright (c) 2015年 陈亚东. All rights reserved. // #include <iostream> using namespace std; void Swap(int& a, int& b) { int tmp = a; a = b; b = tmp; } int Partition(int a[], int low, int high) { // 切分点pivot必须为第一个或最后一个,不能为中间的 int pivot = a[low]; int i = low, j = high; // i!=low+1;因为无法排序4,3,2,1这种, 如i < 跳出 while (i < j) { // 必须先减才行,否则i可能不是low了,找到右边第一个最小的 1,4,3,2找到1 while ( (i < j) && a[j] >= pivot ) { --j; }; while ( (i < j) && a[i] <= pivot ) { // 找到左边第一个最大的 ++i; }; if (i >= j) // 只是为了防止再次交换 break; Swap(a[i], a[j]); } Swap(a[low], a[i]); return i; // j是小于pivot的最大index } void QuickSort(int a[], int low, int high) { if (low < high) { int partition = Partition(a, low, high); cout <<partition << endl; QuickSort(a, low, partition-1); QuickSort(a, partition+1, high); } } int main(int argc, const char * argv[]) { //int a[] = {4,1,2,6,9,5,3,4,6}; // int a[] = {5,4,3,2,1}; int a[] = {1,2,3,4,5}; int len = sizeof(a) / sizeof(int); QuickSort(a,0,len-1); for (int i = 0; i < len; ++i) cout << a[i] << ","; cout << endl; return 0; }
相关文章推荐
- C++模板快速排序和Stooge排序
- [C++]数据结构:排序算法Part2----快速排序、归并排序、箱子排序、基数排序
- C/C++ 数组排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之堆排序
- C++快速排序
- 2018年第九届蓝桥杯【C++省赛B组】【第五题:快速排序】
- C/C++ qsort()快速排序的用法
- 快速排序的递归和非递归实现 -----C++、JAVA代码实现
- 快速排序C++实现
- 堆排序,快速选择排序,快速选择排序,归并排序的c++实现
- 插入排序、冒泡排序、选择排序、希尔排序、快速排序、归并排序、堆排序和LST基数排序——C++实现
- 快速排序的c++实现
- 快速排序:Sort:QuickSort using C++
- 快速排序 C语言的qsort 以及 C++的 sort
- C++实现常用排序算法(快速排序、冒泡排序、希尔排序、折半插入排序、直接插入排序)
- 数据结构---快速排序---java与c++实现
- c++学习之--排序3-快速排序
- C++学习笔记(二)——快速排序的库函数实现
- C/C++ 数组排序(平均时间复杂度 O(nlogn))归并、快速、堆、希尔之快速排序
- 快速排序C++实现(递归,非递归)
- 快速排序——C++实现