第一篇博客,分享是最好的记忆。
一直记不住快速排序,今天自己写一遍,写之前看了《大话数据结构》的快排,所以代码和大话的版本基本相同。
写时主要的错误出现在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");
}