快速排序算法(Quicksort)
2024-10-19 01:28:58
快速排序算法是对集合中元素进行排序最通用的算法,俗称快排,其算法的时间复杂度为O(nlgn),空间复杂度为O(1)。
我们举例来对其算法思路进行理解,譬如数组 A = { 4, 8, 1, 2, 9, 7, 3, 0, 5, 6 };
第一步,以最后一个数6为基准,把小于等于6的数挪到数组左边,把大于6的数挪到数组右边。
那么结果为 { 4, 1, 2, 3, 0, 5, 8, 9, 7, 6 },这个时候再做一步,把8和6进行交换,得到{ 4, 1, 2, 3, 0, 5, 6, 9, 7, 8 }把6的最新位置返回。这个时候其实数组被切割成两部分,准确地说,是三部分{ 4, 1, 2, 3, 0, 5 }, { 6 }和{ 9, 7, 8 }.
第二步,对 { 4, 1, 2, 3, 0, 5 }和 { 9, 7, 8 }重复第一步的过程,我们得到
{ 4, 1, 2, 3, 0 }, { 5 }, { 7 }, { 8 }, { 9 }
第三步,再对{ 4, 1, 2, 3, 0 }进行分割,得到 { 0 }, { 1, 2, 3, 4 }
第四步,再对{ 1, 2, 3, 4 }进行分割,得到{ 1, 2, 3 }和{ 4 }
第五步,对{ 1, 2, 3 }进行分割,得到{ 1, 2 }和{ 3 }
第六步,对{ 1, 2 }进行分割,得到{ 1 }和{ 2 }
C实现代码如下
#include <stdio.h> #define LEN 10 int partition(int *arr, int start, int end)
{
int pivot = arr[end];
int i = start;
int j;
int tmp;
for (j = start; j < end; ++j) {
if (arr[j] <= pivot) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
++i;
}
}
arr[end] = arr[i];
arr[i] = pivot;
return i;
} int quicksort(int *arr, int start, int end)
{
int pivot_location;
if (start < end) {
pivot_location = partition(arr, start, end);
quicksort(arr, start, pivot_location - );
quicksort(arr, pivot_location + , end);
}
} int main()
{
int i;
int arr[LEN] = { , , , , , , , , , };
quicksort(arr, , LEN - );
for (i = ; i < LEN; ++i)
printf("%d\n", arr[i]);
return ;
}
Java实现代码如下
public class QuickSort { // Sort a list of numbers in an array within [start, end]
public void quickSort(int[] A, int start, int end) {
if (start < end) {
int pivotLocation = partition(A, start, end);
quickSort(A, start, pivotLocation - 1);
quickSort(A, pivotLocation + 1, end);
}
} // Select A[end] as the pivot, separate the array into two parts.
private int partition(int[] A, int start, int end) {
int pivot = A[end];
int i = start;
for (int j = start; j < end; ++j) {
if (A[j] <= pivot) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
++i;
}
} A[end] = A[i];
A[i] = pivot;
return i;
} public static void main(String[] args) {
QuickSort q = new QuickSort();
int[] A = { 4, 8, 1, 2, 9, 7, 3, 0, 5, 6 };
q.quickSort(A, 0, A.length - 1);
for (int i = 0; i < A.length; ++i) {
System.out.println(A[i]);
}
} }
最新文章
- 【转】oracle 监听静态注册举例解析
- HTML5移动Web开发(四)——移动设计
- hadoop 突然断电数据丢失问题
- C语言的函数
- C# WinForm 中Console 重定向输出到ListBox控件中显示
- Go defer延迟执行
- WPF中的一些常用类型转换
- iOS推送介绍
- 如何解决This system is not registered with RHN.
- Android分享到微信等社交平台教程
- 9、外观模式(Facade)
- 微信开发模式 api 接口文档简介
- 201521123045 《Java程序设计》第4周学习总结
- JavaScript基础系列
- (字符串 数组 递归 双指针) leetcode 344. Reverse String
- Jenkins 部署自动化测试脚本(15)
- R语言-图形辅助
- 人人中的 shiro权限管理 简单说明
- openstack 之~keystone之HTTP协议
- svn执行update操作后出现:Error : Previous operation has not finished; run &#39;cleanup&#39; if it was interrupted.
热门文章
- [置顶] app后端设计--总目录
- curl以cookie的方式登录
- linux分享四:cron系统
- SVN不显示对号的解决方法
- CentOS编绎gcc
- 【Unity】11.8 关节
- 基于 Promise 的 HTTP 请求客户端 axios
- /etc/ssh/sshd_config 关建字:PermitRootLogin no 禁示以root身份登录服务器
- [SQL in Azure] Configure a VNet to VNet Connection
- javascript基础拾遗(八)