java算法2 快速排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AngeloWolf/article/details/52234556
package com.angelo;


import java.util.Random;
import java.util.Scanner;


public class QuickSort {
/*通过一次排序将要排序的数据分成两部分,
* 其中一部分的数永远比另外一部分的数据要小,然后按此继续递归
* */
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入数组大小:");
int k = sc.nextInt();
int array[] = new int[k];
for (int i = 0; i < array.length; i++) {
Random rd = new Random();
int s = rd.nextInt(30);
array[i] = s;
}
System.out.println("数组排序之前:");
print(array);
System.out.println("数组排序之后:");
quickSort(array,0,array.length-1);
print(array);
}
    public static void print(int[] a){
    for(int i=0;i<a.length;i++){
    System.out.print(a[i]+"\t");
    }
    System.out.println();
    }
    public static void quickSort(int [] b,int lowIndex,int highIndex){  
        int lo= lowIndex;
        int hi= highIndex;
        int mid;
        if(highIndex>lowIndex){
        mid=b[(lowIndex+highIndex)/2];//确定中间分界点元素值
        while(lo<=hi){
        while(lo<highIndex&&(b[lo]<mid))
        ++lo;//确定不大于分界元素值的最小索引
        while(hi>lowIndex&&(b[hi])>mid)
        --hi;//确定大于分界元素的最大索引
        if(lo<=hi){   //如果最小索引和最大索引没有重叠
        swap(b,lo,hi);
        lo++;
        hi--;
        }  
        }
        if(lowIndex<hi)
        quickSort(b,lowIndex,hi);
        if(lo<highIndex)
        quickSort(b,lo,highIndex);
        } 
    }    
    public static void swap(int sortArray[],int i,int j){
    int temp = sortArray[i];
    sortArray[i] = sortArray[j];
    sortArray[j]=temp;
    }
}

猜你喜欢

转载自blog.csdn.net/AngeloWolf/article/details/52234556