快速排序

.


[img]http://dl.iteye.com/upload/picture/pic/89066/a8b30215-61e2-3c45-8778-97dff13bf6b9.jpg[/img]



package com.cdl.algorithem;

import java.util.Arrays;
import java.util.Random;

/**
* 参考:<BR>
* 1.http://www.iteye.com/topic/805043<BR>
* 2.视频:舞动的排序算法 快速排序 http://www.56.com/u61/v_NjczMjQ5Nzg.html<BR>
* 3.视频: 动画http://video.sina.com.cn/v/b/43015877-1731942570.html<BR>
*
* @author ocaicai@yeah.net
* @date: 2011-4-30
*/
public class QickSortTest {

public static void main(String[] args) {
int[] emptyArray = new int[10];// 定义一个数组
int[] targetArray = initArray(emptyArray);// 初始化数组
qickSort(targetArray, 0, targetArray.length - 1);// 排序数组
System.out.println("排序后的数组:" + Arrays.toString(targetArray));// 打印最后的数组

}

/** 初始化数组:使用随机数为数组赋值 */
private static int[] initArray(int[] array) {
Random random = new Random();
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) - random.nextInt(100);
}
System.out.println("排序前的数组:" + Arrays.toString(array));
return array;
}

/** 交换两索引处的值 */
private static void swap(int[] array, int oneIndex,
int anotherIndex) {
int tempValue = array[oneIndex];
array[oneIndex] = array[anotherIndex];
array[anotherIndex] = tempValue;
}

/** 对某一次找出中轴的排序 */
private static int sortOnce(int[] array, int lowIndex, int highIndex) {

int pivotIndex = lowIndex;
int pivotValue = array[pivotIndex];

while (lowIndex < highIndex) {
while (lowIndex < highIndex && pivotValue <= array[highIndex]) {
highIndex--;
}
swap(array, pivotIndex, highIndex);
pivotIndex = highIndex;

while (lowIndex < highIndex && array[lowIndex] <= pivotValue) {
lowIndex++;
}
swap(array, lowIndex, pivotIndex);
pivotIndex = lowIndex;
}
return pivotIndex;
}

/**
* 递归进行排序<BR>
* 找出中轴后然后分治成两组,分别再次递归<BR>
* */
private static void qickSort(int[] array, int lowIndex, int highIndex) {
if (lowIndex < highIndex) {
int privotIndex = sortOnce(array, lowIndex, highIndex);
qickSort(array, lowIndex, privotIndex - 1);
qickSort(array, privotIndex + 1, highIndex);
}
}
}




[color=red]输出结果:[/color]



test1:

原数组:[-41, 21, -38, 71, -26, -12, -57, -25, 19, 50]
排序后的数组:[-57, -41, -38, -26, -25, -12, 19, 21, 50, 71]

test2:

原数组:[-10, 8, 7, 31, -49, 9, 30, -79, 64, 44]
排序后的数组:[-79, -49, -10, 7, 8, 9, 30, 31, 44, 64]

...




.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值