//
// 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++版
最新推荐文章于 2024-03-09 17:43:16 发布