MySort_NC140

排序

描述

给定一个数组,请你编写一个函数,返回该数组排序后的形式。

解题

Solution1

/**
 * 排序算法
 * 快速排序
 */
public class Solution {
    public static void main(String[] args) {
        int[] arr={5,1,6,2,5};
        System.out.println(arr[0]+" "+arr[1]+" "+arr[2]+" "+arr[3]+" "+arr[4]);
        MySort1_NC140.Solution2 s1 = new MySort1_NC140.Solution2();
        arr = s1.MySort(arr);
        System.out.println(arr[0]+" "+arr[1]+" "+arr[2]+" "+arr[3]+" "+arr[4]);

    }
    public int[] MySort (int[] arr){
        if(arr == null || arr.length ==1) return arr;
        quickSort(arr,0,arr.length-1);
        return arr;
    }
    public void quickSort(int[] arr,int low,int height){
        if(low>=height) return;
        int i=low,j=height;
        int cur=arr[low];
        while (i<j){
            while (i<j&&arr[j]>=cur) j--;//先从右边遍历
            while (i<j&&arr[i]<=cur) i++;
            if (i<j){
                int temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
        arr[low]=arr[i];
        arr[i]=cur;
        quickSort(arr,low,j-1);
        quickSort(arr,j+1,height);
    }
}

Solution2

/**
 * 快速排序算法
 * 定位
 */
public class Solution2 {

    public int[] MySort(int[] arr){
        if(arr == null || arr.length ==1) return arr;
        Solution2 solution2 = new Solution2();
        solution2.quickSort(arr,0,arr.length-1);
        return arr;
    }
    public void quickSort(int[] arr,int low,int height){
        if (low<height){
            int point=partition(arr,low,height);
            quickSort(arr,low,point-1);
            quickSort(arr,point+1,height);
        }
    }
    public int partition(int[] arr,int low,int height){
        int first=arr[low];
        while (low<height){
            while (low<height&&arr[height]>=first) height--;
            swap(arr,low,height);//交换
            while (low<height&&arr[low]<=first) low++;
            swap(arr,low,height);
        }
        return low;
    }
    private void swap(int[] arr,int left,int right){
        int temp=arr[left];
        arr[left]=arr[right];
        arr[right]=temp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值