【C++】數據結構之快速排序算法

要求:

  1. 把十六個隨機數字按照升序排序
  2. 使用快速排序的方法
// 快速排序.cpp : 定義控制檯應用程序的入口點。
//

#include"stdafx.h"
#include<iostream>
#include<time.h>
using namespace std;

const int SIZE = 16;

//初始化數組
void Init(int *arr)
{
	srand(time(0));
	for (int i = 1; i <= SIZE; i++)
	{
		arr[i] = rand() % (99 - 10 + 1) + 10;
	}
}

//輸出數組
void OutArr(int *arr)
{
	for (int i = 1; i <= 16; i++)
	{
		cout << arr[i] << '\t';
	}
	cout << endl;
}

// 找標杆位置
int Partition(int *a, int low, int high)
{
	a[0] = a[low];
	int p = a[0];
	while (low < high)
	{
		while (low < high&& a[high]>=p)
		{//如果處於右邊的值比標杆值大,那麼指針指向前一個位置
			high--;
		}
		//右邊的值比標杆值小,循環跳出,a[low]存放該值
		a[low] = a[high];
		while (low < high&&a[low]<=p)
		{//如果處於左邊的值比標杆值小,那麼指針指向後一個位置
			low++;
		}
		//左邊的值比標杆值大,循環跳出,a[high]存放該值
		a[high] = a[low];
	}
	a[low] = a[0];
	return low;//返回標杆值位置
}

void Quick(int *a, int low, int high)
{
	int p;//標杆值
	if (low < high)
	{//遞歸二分排序
		p = Partition(a, low, high);
		if (low < p - 1)//標杆值左邊的值進行排序
			Quick(a, low, p - 1);
		if (p + 1 < high)//標杆值右邊的值進行排序
			Quick(a, p + 1, high);
	}
}

int main()
{
	int arr[SIZE+1];//聲明數組
	Init(arr);		//初始化數組
	OutArr(arr);	//輸出數組
	Quick(arr, 1, SIZE);//快速排序
	OutArr(arr);	//輸出排序後的數組
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章