快速排序(c语言实现)

#include 

#define T 1
#define F 0
#define MAXSIZE 10		//要排序数组个数的最大值

typedef struct
{
	int r[MAXSIZE + 1];	//存储要排序数组,r[0]用作哨兵或临时变量
	int length;
}SqList;

void swap(SqList *L, int i, int j)
{
	int temp = L->r[i];
	L->r[i] = L->r[j];
	L->r[j] = temp;
}

//交换顺序表L中子表的记录,使枢轴记录到位,并返回其所在位置
//此时在它之前(后)的记录均不大(小)于它
int partition(SqList *L, int low, int high)
{
	int pivotkey;
	pivotkey = L->r[low];					//用子表的第一个记录作枢轴记录
	while (low < high)						//从表的两端交替向中间扫描
	{
		while (low < high && L->r[high] >= pivotkey)
			high--;
		swap(L, low, high);					//将枢轴记录小的记录交换到低端
		while (low < high && L->r[low] <= pivotkey)
			low++;
		swap(L, low, high);					//将比枢轴记录大的记录交换到高端
	}
	return low;								//返回枢轴所在位置
}

void QSort(SqList *L, int low, int high)
{
	int pivot;
	if (low < high)
	{
		pivot = partition(L, low, high);	//将L->r[low..high]一分为二
											//算出枢轴值pivot
		QSort(L, low, pivot-1);				//对低子表递归排序
		QSort(L, pivot+1, high);			//对高子表递归排序
	}
}

void quickSort(SqList *L)	//对顺序表L作快速排序
{
	QSort(L, 1, L->length);
}

int main()
{
	int i;
	SqList L;
	L.length = 10;
	for (i = 1; i < L.length+1; i++)
	{
		L.r[i] = i;
	}
	L.r[5] = 100;
	L.r[7] = 90;
	for (i = 1; i < L.length+1; i++)
	{
		printf("%d ", L.r[i]);
	}		
	quickSort(&L);
	printf("\n");
	for (i = 1; i < L.length+1; i++)
	{
		printf("%d ", L.r[i]);
	}
	printf("\n");
	return 0;
}

运行结果:


数组表示:

#include 

void swap(int a[], int i, int j)
{
	int temp = a[i];
	a[i] = a[j];
	a[j] = temp;
}

int partition(int a[], int low, int high)
{
	int pivotkey;
	pivotkey = a[low];//单纯的记录值
	while (low < high)//以pivoekey为交换媒介(枢轴),将大于它的放在后边,小于它的放在前面
	{
		while (low < high && a[high] >= pivotkey)//条件判断 low < high
			high--;
		swap(a, low, high);
		while (low < high && a[low] <= pivotkey)
			low++;
		swap(a, low, high);
	}
	return low;//返回枢轴所在位置
}

void QSort(int a[], int low, int high)
{
	int pivot;
	if (low < high)//是 if 
	{
		pivot = partition(a, low, high);//将a[]一分为二

		QSort(a, low, pivot - 1);//对低子表递归排序
		QSort(a, pivot + 1, high);//对高子表递归排序
	}
}

void quickSort(int a[], int low, int high)
{
	QSort(a, low, high);
}

int main()
{
	int i;
	int a[] = {1,2,5,7,9,6,4,2,6,1};
	quickSort(a, 0, 9);
	for (i = 0; i < 10; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
	return 0;
}

你可能感兴趣的:(数据结构)