c++快速排序

快速排序实际上是改进的冒泡排序,冒泡排序每次交换相邻的两个位置的数据,而快速排序则可以跨位置交换顺序。每一轮快速排序会将一个数字安排到其正确的位置,若每次取第一个数字为基准数,则首先从最后一个位置查找并将当前查找位置记为s1,后从最前面的位置查找并将当前查找位置记为s2,重复这两个步骤,直至s1<=s2,退出进行下一轮快速排序。

/**
 *Copyright @ 2019 Zhang Peng. All Right Reserved.
 *Filename:
 *Author: Zhang Peng
 *Date:
 *Version:
 *Description:快速排序
**/

#include<iostream>
using namespace std;
void swap(int * data, int order1, int order2)
{
	int temp = data[order1];
	data[order1] = data[order2];
	data[order2] = temp;
}

int partition(int *data,int length, int start, int end)
{
	int compareVlaue = data[start],compareIndex=start;
	int forward = start, back = end;

	cout << "待排序元素" << endl;
	for (int i = start; i <= end; i++)
	{
		cout << data[i] << " ";
	}
	cout << endl;

	int num = 0;

	while (forward < back)
	{
		if (num % 2 == 0)
		{
			for (int i = back; i >= forward; i--)
			{
				if (data[i] < compareVlaue)
				{
					swap(data, compareIndex, i);
					back = i;
					compareIndex = i;
					break;
				}
				else
				{
					back = i;
				}
			}
		}
		else
		{
			for (int i = forward; i <= back; i++)
			{
				if (data[i] > compareVlaue)
				{
					swap(data, compareIndex, i);
					forward = i;
					compareIndex = i;
					break;
				}
				else
				{
					forward = i;
				}


			}
		}
		
		num++;
	}

	return compareIndex;
}

void quicksort(int * data, int length, int start, int end)
{
	if (start == end)
		return;
	int centerIndex = partition(data, length, start, end);
	int length_left = centerIndex - start;
	int length_right = end - centerIndex;
	if (length_left > 1)
	{
		quicksort(data, length_left, start, centerIndex - 1);
	}
	if (length_right > 1)
	{
		quicksort(data, length_right, centerIndex + 1, end);
	}
	
	
}
int main()
{
	int originaldata[] = { 6,1,2,7,9,3,4,5,10,8};
	

	//partition(originaldata, 4, 6, 9);
	quicksort(originaldata, 10, 0, 9);
	
	cout << "排序后" << endl;
	for (int i = 0; i < 10; i++)
	{
		cout << originaldata[i] << " ";
	}
	cout << endl;

    system("pause");
    return 0;
}

点赞