package com.xj.www.sort;
/**
* 快速排序算法
*
* @author xiongjing
*
*/
public class QuickSort {
/**
* 快速排序算法具体流程实现如下: 1.首先设定一个分界值,通过该分界值将数组分成左右两部分。
* 2.将大于等于分界值的数据集中到数组右边,小于分界值的数据集中到数组的左边。 此时,左边部分中各元素都小于等于分界值,而右边部分中各元素都大于等于分界值。
* 3.然后,左边和右边的数据可以独立排序,对于左侧的数组数据,又可以取一个分界值,将该
* 部分数据分成左右两部分,同样将左边放置较小值,右边放置较大值,同理,右侧也做类似处理。
* 4.重复上述过程,可以看出明着说一个递归定义。通过递归将左侧部分排好序后,在递归排好右
* 侧部分的顺序。当左、右两部分各数据排序完成后,整个数组的排序也就完成了。
*/
final static int SIZE = 18;
// 算法具体实现
public static void quick(int[] arr, int left, int right) {
int f, t, rtemp, ltemp;
ltemp = left;
rtemp = right;
// 分界值
f = arr[(right + left) / 2];
while (ltemp < rtemp) {
while (arr[ltemp] < f) {
++ltemp;
}
while (arr[rtemp] > f) {
--rtemp;
}
if (ltemp <= rtemp) {
t = arr[ltemp];
arr[ltemp] = arr[rtemp];
arr[rtemp] = t;
--rtemp;
++ltemp;
}
}
if (ltemp == rtemp) {
ltemp++;
}
if (left < rtemp) {
// 递归调用
quick(arr, left, ltemp - 1);
}
if (ltemp < right) {
// 递归调用
quick(arr, rtemp + 1, right);
}
}
// 字符串排序
public static void quickSort(String[] arr, int left, int right) {
String f, t;
int rtemp, ltemp;
ltemp = left;
rtemp = right;
// 分界值
f = arr[(right + left) / 2];
while (ltemp < rtemp) {
while (arr[ltemp].compareTo(f) < 0) {
++ltemp;
}
while (arr[rtemp].compareTo(f) > 0) {
--rtemp;
}
if (ltemp <= rtemp) {
t = arr[ltemp];
arr[ltemp] = arr[rtemp];
arr[rtemp] = t;
--rtemp;
++ltemp;
}
}
if (ltemp == rtemp) {
ltemp++;
}
if (left < rtemp) {
// 递归调用
quickSort(arr, left, ltemp - 1);
}
if (ltemp < right) {
// 递归调用
quickSort(arr, rtemp + 1, right);
}
}
// 程序主入口
public static void main(String[] args) {
// int[] shuzu = new int[SIZE];
String[] arr = new String[] { "One", "World", "Drem", "Beijing", "Olympic" };
int i;
// for (i = 0; i < SIZE; i++) {
// shuzu[i] = (int) (100 + Math.random() * (100 + 1));
// }
System.out.println("排序前的数组为:");
for (i = 0; i < arr.length; i++) {
// System.out.print(shuzu[i] + " ");
System.out.print(arr[i] + " ");
}
System.out.print("\n");
// quick(shuzu, 0, SIZE - 1);
quickSort(arr, 0, arr.length - 1);
System.out.println("排序后的数组为:");
for (i = 0; i < arr.length; i++) {
// System.out.print(shuzu[i] + " ");
System.out.print(arr[i] + " ");
}
System.out.print("\n");
}
}
快速排序
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 选择排序 对于任何输入,时间为O(n*n); 冒泡排序 最优(对于升序的数组,因为加入了一个跳出判断):O(n),...
- 欢迎探讨,如有错误敬请指正 如需转载,请注明出处http://www.cnblogs.com/nullzx/ 1....
- 冒泡排序 大的下沉,小的上浮。 每次循环都从头(0)开始比较到(attr.length-循环次数)位置,每次...