快速排序

第一篇博客,分享是最好的记忆。

一直记不住快速排序,今天自己写一遍,写之前看了《大话数据结构》的快排,所以代码和大话的版本基本相同。

写时主要的错误出现在MyQSort( )函数内,if(low < high) 写成了while(low < high), 结果陷入了死循环。


#include <stdio.h>

const int len = 10;  // 数组长度
void Swap(int a[], int i, int j);  
int Partition(int a[], int low, int high); // 调整数组,并返回枢轴位置
void MyQSort(int a[], int low, int high);  // 排序
void PrintArray(int a[], int len);         // 输出

void main()
{
	int arr[10] = {60, 20, 40, 80, 70, 50, 10, 90, 30, 0};
	printf("Before:  ");
	PrintArray(arr, len);
	MyQSort(arr, 0, len-1);
	printf("After:  ");
	PrintArray(arr, len);
}

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

int Partition(int a[], int low, int high)
{
	int pivot = a[low];
	while (low < high)
	{
		while (low < high && a[high] > pivot) 
			high--;
		Swap(a, low, high);
		while (low < high && a[low] < pivot)
			low++;
		Swap(a, low, high);
	}
	return low;
}

void MyQSort(int a[], int low, int high)
{
	int pivot;
	if (low < high)  // 最初写成了while(), 结果会陷入了死循环
	{
		pivot = Partition(a, low, high);
		printf("%d,\t", a[pivot]);    // 输出经过一次调整之后的枢轴值
		PrintArray(a, len);           // 打印一次调整之后的数组
		MyQSort(a, low, pivot-1);
		MyQSort(a, pivot+1, high);
	}
}

void PrintArray(int a[], int len)
{
	int i;
	for (i = 0; i < len; i++)
	{
		printf("%d ", a[i]);
	}
	printf("\n");
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值