数据结构排序算法 (六)

2014-11-23 23:24:25 · 作者: · 浏览: 26

quickSort(arr,0,n-1);
for (int i = 0; i < n; ++i)
{
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}

#include
#include
#include

void swap(int *a,int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}

int partition(int *arr,int low,int high)
{
int pivot = arr[low];
while(low < high)
{
while(low < high && arr[high] >= pivot)
{
high--;
}
if (low < high)
{
swap(&arr[low],&arr[high]);
low++;
}
while(low < high && arr[low] <= pivot)
{
low++;
}
if(low < high)
{
swap(&arr[low],&arr[high]);
high--;
}
}

return low;

}
void quickSort(int *arr,int low,int high)
{
int pivotpos;
if (low < high)
{
pivotpos = partition(arr,low,high);
quickSort(arr,low,pivotpos-1);
quickSort(arr,pivotpos+1,high);
}
}


int main(int argc, char const *argv[])
{
int n ;
printf("please input the length of arr:\n");
scanf("%d",&n);
//int *arr = (int*)malloc(n * sizeof(int));
int arr[n];
printf("please input %d numbers for each elements\n", n);
for(int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);

}
quickSort(arr,0,n-1);
for (int i = 0; i < n; ++i)
{
printf("%d ",arr[i]);
}
printf("\n");
return 0;
}