根据您的代码,即使是理解起来有点复杂的分区,qsort 函数也很好!我猜你的问题是交换功能!这是一个使用易于理解的分区函数实现的工作代码:
void swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
/* the aim of the partition is to return the subscript of the exact */
/* position of the pivot when it is sorted */
// the low variable is used to point to the position of the next lowest element
int partition(int arr[], int first, int last)
{
int pivot = arr[last]; // changed the pivot
int low = first;
int i = first; // changed
while(i <= last-1 ){// or you can do for(i=first;i<last;i++)
if(arr[i] < pivot){
swap(&arr[i], &arr[low]);
low++;
}
i++;
}
swap(&arr[last], &arr[low]);
// after finishing putting all the lower element than the pivot
// It's time to put the pivot into its place and return its position
return low;
}
void quick_sort(int arr[], int first, int last)
{
int pivot_pos;
if(first < last){
pivot_pos = partition(arr, first, last);
quick_sort(arr, first, pivot_pos-1);
quick_sort(arr, pivot_pos+1, last);
}
}
要测试程序,你可以使用下面的 main 函数
int main(int argc, char *argv[])
{
int tab[]={4,53,5,6,7,1};
quick_sort(tab,0,5);
int i=0;
for (i=0;i<6;i++)
{
printf(" %d ",tab[i]);
}
printf("\n");
return 0;
}
它将生成排序后的数组
1 4 5 6 7 53
如果你想看看到底发生了什么这是一个完整的代码:)
#include <stdio.h>
void affiche(int *p,int size);
void swap(int *p, int a, int b)
{
int temp=p[a];
p[a]=p[b];
p[b]=temp;
}
int partition(int *p, int start, int end)
{
int pindex=start;
int pivot=p[end];
int i=0;
for (i=start;i<=end-1;i++)
{
if (p[i]<pivot)
{
printf("swap p[%d] and p[%d] pivot %d\n",i,pindex,pivot);
swap(p,i,pindex);
affiche(p,7);
pindex++;
}
}
printf("==>swap p[%d] and p[%d] pivot %d\n",pindex,end,pivot);
swap(p,pindex,end);
return pindex;
}
void quicksort(int *p,int a,int b)
{
if (a<b)
{
affiche(p,7);
int pindex=partition(p,a,b);
quicksort(p,a,pindex-1);
quicksort(p,pindex+1,b);
}
}
void affiche(int *p,int size)
{
int i=0;
for (i=0;i<size;i++)
{
printf(" %d ",p[i]);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int tab[]={7,2,4,8,4,0,4};
affiche(tab,7);
quicksort(tab,0,6);
affiche(tab,7);
return 0;
}