然后再按从大到小的顺序,依次在第一个位置的两边,按照一左一右的顺序,依次存放剩下的数。例如:input[] = {3, 6, 1, 9, 7} output[] = {3, 7, 9, 6, 1}; input[] = {3, 6, 1, 9, 7, 8} output[] = {1, 6, 8, 9, 7, 3} 1 import java.util.Arrays; 2 public class Solution 3 { 4 /** 5 操作方法 6 */ 7 public static int[] operate(int[] input) 8 { 9 int[] output = new int[input.length]; 10 int k = input.length/2;//用为output的指针 11 quickSort(input,0,input.length-1); 12 for (int i = 0; i < input.length; i++) 13 { 14 output[k] = input[i]; 15 if (k < input.length/2) 16 { 17 k += i+1; 18 } else 19 { 20 k -= i+1; 21 } 22 } 23 return output; 24 } 25 26 /** 27 快速排序 28 */ 29 private static void quickSort(int[] input, int left, int right) 30 { 31 if (left < right) 32 { 33 int pivot = partion(input, left, right); 34 quickSort(input, left, pivot-1); 35 quickSort(input, pivot+1, right); 36 } 37 38 } 39 40 /** 41 大小分开的方法 42 */ 43 private static int partion(int[] input, int left, int right) 44 { 45 int pivotVal = input[left]; 46 while (left < right) 47 { 48 while (left < right && input[right] <= pivotVal) 49 { 50 --right; 51 } 52 input[left] = input[right]; 53 while (left < right && input[left] >= pivotVal) 54 { 55 ++left; 56 } 57 input[right] = input[left]; 58 } 59 input[left] = pivotVal; 60 return left; 61 } 62 63 public static void main(String[] args) 64 { 65 int input1[] = {3, 6, 1, 9, 7}; 66 int input2[] = {3, 6, 1, 9, 7, 8}; 67 System.out.println(Arrays.toString(operate(input1))); 68 System.out.println(Arrays.toString(operate(input2))); 69 } 70 71 }
时间: 2024-10-25 02:45:10