必会的快速排序

版权声明:个人整理,仅供参考,请勿转载,如有侵权,请联系[email protected] https://blog.csdn.net/mooe1011/article/details/89226608

1.快速排序

#include<bits/stdc++.h>
using namespace std;

//严蔚敏版
void printarr(int arr[], int sz) {
	for (int i = 0; i < sz; i++)
	{
		cout << arr[i] << " ";
	}
	cout << endl;
}

void Qsort(int arr[], int low, int high, int sz) {
	if (high <= low) return;
	int i = low;
	int j = high + 1;
	int key = arr[low];
	cout << "low(key)  " << key << "  high  " << arr[high] << endl;
	printarr(arr, sz);
	while (true)
	{
		/*从左向右找比key大的值*/
		while (arr[++i] < key)
		{
			if (i == high) {
				break;
			}
		}
		/*从右向左找比key小的值*/
		while (arr[--j] > key)
		{
			if (j == low) {
				break;
			}
		}
		if (i >= j) break;
		/*交换i,j对应的值*/
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
		cout << "swap i & j " << arr[i] << "  " << arr[j] << endl;
		printarr(arr, sz);
	}
	/*中枢值与j对应值交换*/
	int temp = arr[low];
	arr[low] = arr[j];
	arr[j] = temp;

	cout << "swap low & j " << arr[low] << "  " << arr[j] << endl;
	printarr(arr, sz);

	cout << "Qsort1(" << low << ", " << j - 1 << ")" << endl;
	Qsort(arr, low, j - 1, sz);

	cout << "Qsort2(" << j + 1 << ", " << high << ")" << endl;
	Qsort(arr, j + 1, high, sz);

	cout << endl;
}

int main()
{
	int a[] = { 57, 68, 59, 52, 72, 28, 96, 33, 24, 1 };
	int sz = sizeof(a) / sizeof(a[0]);
	Qsort(a, 0, sz - 1, sz);
	return 0;
}

/*输出
low(key)  57  high  24
57 68 59 52 72 28 96 33 24
swap i & j 24  68
57 24 59 52 72 28 96 33 68
swap i & j 33  59
57 24 33 52 72 28 96 59 68
swap i & j 28  72
57 24 33 52 28 72 96 59 68
swap low & j 28  57
28 24 33 52 57 72 96 59 68
Qsort1(0, 3)
low(key)  28  high  52
28 24 33 52 57 72 96 59 68
swap low & j 24  28
24 28 33 52 57 72 96 59 68
Qsort1(0, 0)
Qsort2(2, 3)
low(key)  33  high  52
24 28 33 52 57 72 96 59 68
swap low & j 33  33
24 28 33 52 57 72 96 59 68
Qsort1(2, 1)
Qsort2(3, 3)


Qsort2(5, 8)
low(key)  72  high  68
24 28 33 52 57 72 96 59 68
swap i & j 68  96
24 28 33 52 57 72 68 59 96
swap low & j 59  72
24 28 33 52 57 59 68 72 96
Qsort1(5, 6)
low(key)  59  high  68
24 28 33 52 57 59 68 72 96
swap low & j 59  59
24 28 33 52 57 59 68 72 96
Qsort1(5, 4)
Qsort2(6, 6)

Qsort2(8, 8)
*/

猜你喜欢

转载自blog.csdn.net/mooe1011/article/details/89226608