交换排序之快速排序(java实现)

java

import java.util.Arrays;


public class QuickSort {

    public static void quickSort(DataWraper[] data){
        System.out.println("开始排序");
        subSort(data,0,data.length-1);
       
    }
    //对data数组中从start到end索引范围的子序列进行处理,
    //使所有小于分界值的放在左面,所有大于分界值的放在右面
    private static void subSort(DataWraper[] data, int start, int end) {
        // TODO Auto-generated method stub
        if(start<end){
            //以第一个元素作为分界值
            DataWraper base=data[start];
            //i从左边开始搜索,搜索大于分界值的元素的索引
            int i=start;
            //j从右边开始搜索,搜索小于分界值的元素的索引
            int j=end+1;
            while(true){
                //找到大于分界值的元素索引,或者i已经到了end处
                while(i<end&&data[++i].compareTo(base)<=0);
                //找到小于分界值的元素索引,或者j已经到了start处
                while(j>start&&data[--j].compareTo(base)>=0);
                if(i<j){
                    swap(data,i,j);
                }else{
                    break;
                }
                System.out.println(Arrays.toString(data));
            }
            //将分界值与和j索引处元素交换
            swap(data,start,j);
            System.out.println(Arrays.toString(data));
            //递归遍历左子序列
            subSort(data, start, j-1);
            //递归遍历右子序列
            subSort(data, j+1, end);
        }
    }
    private static void swap(DataWraper[] data, int i, int j) {
        // TODO Auto-generated method stub
        DataWraper tmp=data[i];
        data[i]=data[j];
        data[j]=tmp;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        DataWraper [] data={
                new DataWraper(21, ""),
                new DataWraper(30, ""),
                new DataWraper(49, ""),
                new DataWraper(30, "*"),
                new DataWraper(16, ""),
                new DataWraper(9, ""),
               
        };
        System.out.println("排序之前:\n"+Arrays.toString(data));
        quickSort(data);
        System.out.println("排序之后:\n"+Arrays.toString(data));
    }

}

结果:

排序之前:
[21, 30, 49, 30*, 16, 9]
开始排序
[21, 9, 49, 30*, 16, 30]
[21, 9, 16, 30*, 49, 30]
[16, 9, 21, 30*, 49, 30]
[9, 16, 21, 30*, 49, 30]
[9, 16, 21, 30*, 49, 30]
[9, 16, 21, 30*, 30, 49]
排序之后:
[9, 16, 21, 30*, 30, 49]

以上是 交换排序之快速排序(java实现) 的全部内容, 来源链接: utcz.com/z/390482.html

回到顶部