简体   繁体   中英

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

I'm still a student and I have an assignment in Java where I have to sort an array that compares the first element from the last element until the array is sorted out from highest to lowest. I already did some of the algorithm but it seems it jumps swap number 2 and proceeds to swap3. The program should run like this.

10 , 3, 7, 15, 9

10 , 3, 7, 15 , 9

15 , 3, 7 , 10, 9 - 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

So here is my algorithm doing this:

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");
}

The output is:

Sorting array first and last elements

sorting....

15,3,7,10,9,sorting....

15,10,7,9,3,sorting....

15,10,9,7,3,sorting....

15,10,9,7,3,sorting....

15,10,9,7,3,sorted

It does sort but it jumps the swap number 2 and proceeds to swap number 3. How can i do this correctly that the output shows and does not jump the swap number 2?

The outer loop goes from the first element until the end.

The inner loop goes from the last element until the index of the outer loop.

You print the content of the array after the inner loop runs. That is, you print the content one time per iteration of the outer loop. Keep in mind that during the inner loop, multiple swaps can happen. For example two swaps happen when f=1 .

If you want to print the state after each swap, then do just that, in the inner loop:

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));
    }
  }
}

This will print:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM