欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

快速排序(c++实现)

程序员文章站 2022-05-22 19:54:40
...

partaion函数用于找到分节点,然后利用分治的想法将数组排序。

#include"pch.h"
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int partaion(int a[], int start, int end)
{
	int label = a[end];
	int slow = start - 1;
	for (int fast = start; fast < end; fast++)
	{
		if (a[fast] < label)
		{
			int temp;
			slow++;
			temp = a[slow];
			a[slow] = a[fast];
			a[fast] = temp;
		}
	}
	a[end] = a[slow + 1];
	a[slow + 1] = label;
	return slow + 1;
}
void quickSort(int a[], int start, int end)
{
	if (start < end)
	{
		int part = partaion(a, start, end);
		quickSort(a, start, part - 1);
		quickSort(a, part + 1, end);
	}
}
int main()
{
	srand(time(0));
	int a[10];
	for (int i = 0; i < 10; i++)
	{
		a[i] = rand() % 10;
		printf_s("%d", a[i]);
		if (i != 9)
		{
			cout << " ";
		}
		else
			cout << endl;
	}
	quickSort(a, 0, 9);
	for (int i = 0; i < 10; i++)
	{
		printf_s("%d", a[i]);
		if (i != 9)
		{
			cout << " ";
		}
		else
			cout << endl;
	}
}

 

相关标签: data structure