排序算法——快速排序
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;
}
快速排序算法是不稳定的排序,例如, 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;
}
相关文章推荐
- Search for a Range ——LeetCode
- vm10.0.2+hadoop2.5.1+jdk8+centos6.6 转(非原创哈)自己收藏看的
- 刺激的摩托飞艇 区间型动态规划
- 优化WebView nativeOnDraw failed; clearing to background color及其根本原因
- Java编写图片上传服务器
- 冒泡排序
- 题解 cf div2 193B
- C++继承、虚继承、虚函数类的大小问题
- [转]C#操作INI文件
- ubuntu 安装Bochs
- 为 Lync 2013 前端升级 Sql Server 2012 Express SP1
- C#中使用WeiFenLuo.WinFormsUI.Docking.dll实现窗口停靠效果
- iOS开发Delegate,Notification,Block使用心得
- Yii2同时搜索多个字段
- LeetCode题目总结分类
- 基础R绘图
- 图形界面配置heartbeat高可用集群
- 【code】flex_抛自定义事件
- Yii2让关联字段支持搜索功能
- 三亚六月各平台团购数据对比