Quick Sort (C++)

#include  
#include 

using namespace std;

int partition(vector& num, int first, int last) {

	int k = first;
	int ntemp = num[last];              //这里设置个temp变量, 作为一个pivot的培养对象
	for (int i = first; i < last; i++) {
		if (num[i] <= ntemp) {
			swap(num[i], num[k++]);
		}
	}
	swap(num[k], num[last]);  //这里不要用pivot  要用num[last] !!!!
	return k;
}

void quickSort(vector& num, int first, int last) {
	if (last > first) {
		int pivot = partition(num, first, last );
		quickSort(num, first, pivot - 1);
		quickSort(num, pivot + 1, last );
	}
}

void printVector(vector& num) {
	for (int i = 0; i < num.size(); i++) {
		cout << num[i] << " ";
	}
	cout << endl;
}

int main() {
	vector A = { 3, 2, 6, 4 };
	
	cout << "======Input======" << endl;
	printVector(A);

	cout << "======Output======" << endl;
	quickSort(A, 0, A.size() - 1);
	printVector(A);

	
	return 0;
}

 

你可能感兴趣的:(数据结构与算法)