java之快速排序
直接上代码:
-----------------------------------------------------
package com.mylearn;
/**
* 快速排序法,基本思想:选择一个基准元素,通常选择第一个元素或者最后一个元素,通过一趟扫描,将待排序列分成两部分,一部分比基准元素小,一部分大于等于基准元素
* ,此时基准元素在其排好序后的正确位置,然后再用同样的方法递归地排序划分的两部分。
*
* @author H
*
*/
public class KuaiSu {
// 快速排序主程序
public static void kuaisu(int[] arr) {
quickSort(arr, 0, arr.length - 1);
}
// 快速排序法递归,表明要排序的数组,以及起始索引
private static void quickSort(int[] arr, int first, int last) {
// 只要最后一个大于第一个的索引
if (last > first) {
// 将数组分为两部分,并且选择第一个为主元
int pivotIndex = partition(arr, first, last);
// 对主元分开的两个子数组进行排序
quickSort(arr, first, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, last);
}
}
// 寻找主元并且划分数组的部分
public static int partition(int[] list, int first, int last)// 划分数组为两部分
{
// 选择第一个为主元
int pivot = list[first];
// 后面将数组划分为大于主元和小于主元的两大块
int low = first + 1;
int high = last;
// 如果high大于low
while (high > low) {
// 如果low的元素小于pivot就继续推进
while (low <= high && list[low] <= pivot)
low++;
// 如果high的元素大于pivot就继续后退
while (low <= high && list[high] > pivot)
high--;
// 否则,说明出现了相反情况,则交换两个元素
if (high > low)// 当list[high]
first && list[high] >= pivot)
high--;
// 如果一开始选的主元比最后一个high元素要大
if (pivot > list[high]) {
list[first] = list[high];
list[high] = pivot;
return high;
} else
return first;
}
public static void main(String[] args) {
// 声明数组
int[] arr = { 1, 2, 3, 0, 1, 5, -1, 2 };
// 调用快速排序算法
kuaisu(arr);
// 输出结果
for (int element : arr)
System.out.println(element);
}
}