我需要以特定的“降序”順序對陣列進行排序:元素交替插入到陣列的開頭或結尾。
如果元素的降序是a>b>c>d,那么最終的陣列應該是
[] -> [a,_,_,_] -> [a,_,_,b] -> [a,c,_,b] -> [a,c,d,b]
樣品 1
輸入:[4,13,8,9,7,1,6]
輸出:[13,8,6,1,4,7,9]
樣品 2
輸入:[16,23,7,11,3,14]
輸出:[23,14,7,3,11,16]
我怎樣才能找到解決這個問題的方法?
我嘗試只對第一個索引進行排序,但我也需要對最后一個索引進行排序。
public static void BubbleSort_First(int[] arr,int first){
int n = arr.length;
for (int i = 0; i < n - 1; i )
for (int j = 0; j < n - i - 1; j )
if(arr[i]==first){
if (arr[j] < arr[j 1]) {
// swap arr[j 1] and arr[j]
int temp = arr[j];
arr[j] = arr[j 1];
arr[j 1] = temp;
}
}
}
uj5u.com熱心網友回復:
也許您可以在陣列的排序版本上向后迭代,同時分別在陣列的前面和后面保留兩個指向下一個位置的指標:
import java.util.Arrays;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] a1 = {4, 13, 8, 9, 7, 1, 6};
System.out.printf("Input1 = %s%n", Arrays.toString(a1));
System.out.printf("Output1 = %s%n", Arrays.toString(frontBackSorted(a1)));
System.out.println();
int[] a2 = {16, 23, 7, 11, 3, 14};
System.out.printf("Input2 = %s%n", Arrays.toString(a2));
System.out.printf("Output2 = %s%n", Arrays.toString(frontBackSorted(a2)));
}
public static int[] frontBackSorted(int[] array) {
int[] sortedArray = IntStream.of(array).sorted().toArray();
int n = array.length;
int[] result = new int[n];
int i = 0, j = n - 1, k = n - 1;
boolean front = true;
while (i <= j) {
if (front) {
result[i ] = sortedArray[k--];
} else {
result[j--] = sortedArray[k--];
}
front = !front;
}
return result;
}
}
輸出:
Input1 = [4, 13, 8, 9, 7, 1, 6]
Output1 = [13, 8, 6, 1, 4, 7, 9]
Input2 = [16, 23, 7, 11, 3, 14]
Output2 = [23, 14, 7, 3, 11, 16]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463762.html
