您的位置:首页 > 其它

排序算法——快速排序

2015-06-08 01:08 344 查看
快速排序算法的平均时间性能为(O(n *log n)),是最快的排序算法之一,但是由于使用了递归,需要的辅助空间远远大于插入排序。

快速排序算法是不稳定的排序,例如, 4 5 5 1, 第一趟排序时,第一个5 和1会交换。

基本思想:

1、 采用分治法,每次选择数组中一个元素(通常为第一个)作为关键字,将数组分成两个段,左边部分元素都小于关键字,右边部分元素都大于关键字。

2.、采用递归的方法,分别对左边部分、右边部分依次递归。

代码如下:

// arr 为需要排序的数组,low 和 high 表示数组的下标,需要从low 到high 进行排序

void qSort(int arr[], int low , int high)

{

int pivot;

if(low < high)//个数大于1

{

pivot = partition( arr, low, high); //将数组分段

qSort(arr ,low ,pivot - 1);//左边部分递归

qSort(arr, pivot + 1, high);//右边部分递归

}

}

//函数目的是需要 将选定的关键字 插入到合适的位置,使数组分段,并返回该元素的位置

int partition(int arr[] ,int low , int high)

{

int pivot;

int index;

if(low > high)

{

puts("error param");

exit(1);

}

pivot = arr[low];//将第一个元素设为基准,此时需要从右边指针开始移动,这样能保证left == right时,left指向的是比基准值更小的数

index = low; //保存基准的索引

while(low < high)

{

while((arr[high] >= pivot)&& (low < high))

{

high--;

}

while((arr[low] <= pivot)&&(low < high))

{

low++;

}

if( low < high)

{

swap(&arr[high],&arr[low]);

}

}

//把left == right处的值与 基准位置的值交换,将基准值放到中间

arr[index] = arr[low];//从右边移动的话arr[low] 一定会比arr[index]值小

arr[low] = pivot;

printf("low = %d\n",low);

return low;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: