簡體   English   中英

如何比較首個元素和最后一個元素以降序對數組進行排序

[英]How to sort an array in descending order comparing the first element and the last

我還是一個學生,我在Java中有一個作業,我必須對一個數組進行排序,該數組將比較最后一個元素中的第一個元素,直到該數組從最高到最低進行排序。 我已經做了一些算法,但似乎它會跳過交換編號2並繼續進行swap3。 該程序應這樣運行。

10,3,7,15,9

10,3,7,15,9

15,3,7,10,10 - swap1

15,3,7,10%,9

15,3,7,10%,9

15,9,7,10,3 - swap2

15,10,7,9,3-

15,10,7,9,3-

15,10,7,9,3-

15,10,9,7,3 - swap3

15,10,9,7,3

因此,這是我的算法:

public static void main(String[] args) {
   int array[] = {10,3,7,15,9};
   int f;
   int l;
   int temp;

   System.out.println("Sorting array first and last elements");

   for (f = 0; f < array.length; f++)
   {
       for (l = 4; l > f; l--)
       {
           if (array[f] < array[l])
           {
               temp = array[l];
               array[l] = array[f];
               array[f] = temp;
           }          
       }

       System.out.println("sorting....");

       for (int c = 0; c < array.length; c++) 
           System.out.print(array[c] + ",");
    }

    System.out.println("sorted");
}

輸出為:

排序數組的第一個和最后一個元素

排序....

15,3,7,10,9,排序....

15,10,7,9,3,排序....

15,10,9,7,3,排序....

15,10,9,7,3,排序....

15,10,9,7,3,整理

它會排序,但會跳掉交換號2並繼續進行到交換號3。我如何正確地執行此操作,以便輸出顯示而不跳出交換號2?

外循環從第一個元素到最后一個元素。

內循環從最后一個元素開始直到外循環的索引。

內部循環運行后,您將打印數組的內容。 也就是說,您在外循環的每次迭代中僅打印一次內容。 請記住,在內部循環期間,可能會發生多次交換。 例如,當f=1時發生兩次交換。

如果要在每次交換后打印狀態,請在內部循環中執行以下操作:

for (f = 0; f < array.length; f++) {
  for (l = array.length - 1; l > f; l--) {
    if (array[f] < array[l]) {
      temp = array[l];
      array[l] = array[f];
      array[f] = temp;
      System.out.println(Arrays.toString(array));
    }
  }
}

這將打印:

[15, 3, 7, 10, 9]
[15, 9, 7, 10, 3]
[15, 10, 7, 9, 3]
[15, 10, 9, 7, 3]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM