快速排序的两种实现

快速排序的两个实现,测试用例不多,可能有bug:

/*
* Copyright (c) 2011 alexingcool. All Rights Reserved.
*/
#include <iostream>
#include <iterator>
#include <algorithm>

#define DEBUG
#undef DEBUG

using namespace std;

int array[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3};
const int size = sizeof array / sizeof *array;

void QuickSort(int (&array)[size]);
void _QuickSort(int (&array)[size], int start, int end);
int Partition(int (&array)[size], int start, int end);
int Partition2(int (&array)[size], int start, int end);

void QuickSort(int (&array)[size]) {
	_QuickSort(array, 0, size - 1);
}

void _QuickSort(int (&array)[size], int start, int end) {
	if(start < end) {
    int pivot = Partition2(array, start, end);
	_QuickSort(array, start, pivot - 1);
	_QuickSort(array, pivot + 1, end);
	}
}

int Partition(int (&array)[size], int start, int end) {
 //别一个不小心写出 int pivot = array[end];
	int& pivot = array[end];
	int i = start - 1, j = start;
 
	while(j < end) {
	if(array[j] < pivot) {
		i++;
		swap(array[i], array[j]);
	}
		j++;
	}
	
	swap(array[i + 1], pivot);
	
	return i + 1;
}

int Partition2(int (&array)[size], int start, int end) {
	int& pivot = array[end];
	int j = end - 1;
	int i = start;
 
	while(true) {
		while(i < end && array[i] < pivot)
			i++;
		while(j > 0 && array[j] > pivot)
			j--;
		if(i > j)
			break;
		swap(array[i], array[j]);
	}
	swap(array[i], pivot);
#ifdef DEBUG
	copy(array, array + size, ostream_iterator<int>(cout, " "));
	system("pause");
#endif
	
	return i;
}

void main() {
	cout << "raw array: ";
	copy(array, array + size, ostream_iterator<int>(cout, " "));
	cout << endl;
	QuickSort(array);
	copy(array, array + size, ostream_iterator<int>(cout, " "));
	cout << "finished" << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值