题目描述
给定一个数组,请你编写一个函数,返回该数组排序后的形式
输入:[5,2,3,1,4]
返回值由小到大:[1,2,3,4,5]
返回值由大到小:[5,4,3,2,1]
package com.refinitiv.ciqm.udf; import java.util.*; public class Solution { public static void main(String[] args) { int[] arr = {5,2,3,1,4,7,8}; Solution sl = new Solution(); // 从大到小快速排序 quickSortBigtoSmall(arr,0,arr.length-1); // 从小到大快速排序 quickSortSmalltoBig(arr,0,arr.length-1); System.out.println(Arrays.toString(arr)); } private static void quickSortSmalltoBig(int[] arr,int low,int high){ if (low < high){ int mid = getIndexFromSmallToBig(arr,low,high); quickSortSmalltoBig(arr,low,mid-1); quickSortSmalltoBig(arr,mid +1 ,high); } } private static int getIndexFromSmallToBig(int[] arr,int low,int high){ int index = (low + high) /2; int midNum = arr[index]; swap(arr,index,high); System.out.println("swap1" + Arrays.toString(arr)); while(low < high){ while(low < high && arr[low] <= midNum) { low++; } swap(arr,low,high); while (low < high && arr[high] >= midNum) { high--; } swap(arr,low,high); } return high; } private static void quickSortBigtoSmall(int[] arr,int low,int high) { if(low<high){ // 获取中间点 int mid = getIndexFromBigToSmall(arr,low,high); quickSortBigtoSmall(arr,low,mid -1); quickSortBigtoSmall(arr,mid+1,high); } } private static int getIndexFromBigToSmall(int[] arr,int low,int high){ int index = (low + high) / 2; int midNum = arr[index]; // 无论取的值是哪一个 ,都应该将其放在最后面 swap(arr,index,high); while (low < high){ //左侧值大于或者等于左侧值时,只需要移动指针即可 while (low < high && arr[low] >= midNum) { low++; } swap(arr,low,high); //右侧小于或者等于右侧值是,只需要移动指针即可 while (low < high && arr[high] <= midNum) { high--; } swap(arr,low,high); } return high; } private static void swap(int[] arr,int low,int high){ int temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; } }