package com.haut.gaogeng;
/*
* 快速排序算法的java代码实现
*/
public class QuickSort {
public static void main(String[] args){
int[] a = new int[]{15,7,4,1,5,3,9,2,100,55,6,14,55,73};
//对数组进行全排序
QSort(a, 0, a.length-1);
//输出数组的元素
printArray(a);
}
private static void QSort(int[] a2, int low, int high) {
//用于记录关键字在排序数组中的位置
int pivot ;
//只有low < high时才会有排序的需要
if(low < high){
//将数组一分为二,前半部分比关键字小,后半部分比关键字大
pivot = Partition(a2, low, high);
//对前半部分进递归排序
QSort(a2, low, pivot - 1);
//对后半部分进行递归排序
QSort(a2, pivot + 1, high);
}
}
private static int Partition(int[] a2, int low, int high) {
int key;
//将数组a2第一个位置的数作为关键字
key = a2[low];
//如果是一个数那就没必要排序了
while(low < high){
/*如果是循环到low = high没必要执行high--
* 从数组后面向前找比关键字小的数的下标
* 然后将这位置的数和关键字交换
*/
while(low < high && key <= a2[high])
high--;
swap(a2, low, high);
/*如果是循环到low = high没必要执行low++
* 从数组前面向后找比关键字大的数的下标
* 然后将这位置的数和关键字交换
*/
while(low < high && key >= a2[low]){
low++;
}
swap(a2, low, high);
}
return low;
}
//交换数据
public static void swap(int[] a2, int low, int high){
int temp = 0;
temp = a2[low];
a2[low] = a2[high];
a2[high] = temp;
}
//输出数组的元素
public static void printArray(int[] a){
for(int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
}
}
快速排序算法java代码实现
最新推荐文章于 2024-07-17 10:35:12 发布