對隨機產生的數列進行快速排序

以前在學習快速排序的時候總是理解不夠,導致總是沒辦法記住其使用方法,趁有空重新學習了一下快速排序,作此記錄放遍日後複習及改進。代碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define  ERROR -1

int createRand(const int start, const int end, const int count, int *buf);
int partition(int* buf, int low, int high);
int QSort(int *buf, int low, int high);
int main01()
{
	int a[10];
	//printf("the arry a size is : %d\n", sizeof(a)/sizeof(a[0]));
	createRand(10, 20, sizeof(a) / sizeof(a[0]), a);
	printf("this arry data is :\n");
	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
		printf("%d\n", a[i]);

	printf("==========================================\n");

	QSort(a, 0, 9);
	printf("this arry data after quick sort is :\n");
	for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
		printf("%d\n", a[i]);

	system("pause");
	return 0;
}

//start-end指定隨機數的範圍,buf 存放產生的隨機數(列)
int createRand(const int start, const int end, const int count, int *buf)
{
	if (abs(end - start + 1) < count)
	{
		printf("the count is too long that can't create \n");	//輸入的範圍超過數組的容量,報錯
		return ERROR;
	}

	//隨機數產生的兩個步驟:
	//1、用srand((unsigned int)time(NULL)) 種下時間種子,
	//這裏強制轉換成 unsigned int 是因爲 time() 返回的是 int 型,而srand() 需要的參數是 unsigned int 
	//2、使用 rand() 產生隨機數,rand() 使用公式:rand() % abs(end - start + 1) + start

	srand((unsigned int)time(NULL));	//種下時間種子
	for (int i = 0; i < count; ++i)
	{
		buf[i] = rand() % abs(end - start + 1) + start;	//產生隨機數
	}
	return 0;
}

//快速排序,先對數列進行分區
//buf是需要排序的數組首地址,low-high指定需要排序的範圍
int partition(int* buf, int low, int high)
{
	if (buf == NULL)
		return ERROR;

	int pivotKey = buf[low];	//把數組起始元素作爲 樞軸記錄
	while (low < high)	//此次循環後以 樞軸記錄 爲中心,兩邊是比 樞軸記錄 小或大的值
	{
		while (low < high && pivotKey <= buf[high]) --high;	//從高處查找比 樞軸記錄 更小的值,如發現則交換
		buf[low] = buf[high];
		while (low < high && pivotKey >= buf[low]) ++low;	//從低處查找比 樞軸記錄 更大的值,如發現則交換
		buf[high] = buf[low];
	}
	buf[low] = pivotKey;	//把樞軸記錄的數據填補到此次劃分後的 樞軸位置
	return low;
}

int QSort(int *buf, int low, int high)
{
	if (buf == NULL)
		return ERROR;
	if (low < high)
	{
		int pivotKey = partition(buf, low, high);
		QSort(buf, low, pivotKey - 1);			//遞歸對 低值區 繼續分區
		QSort(buf, pivotKey + 1, high);			//遞歸對 高值區 繼續分區
	}
	return 0;
}

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