I am writing an array sorting program:

int[] myArray = {5, 7, 2, 8, 1, 0, 3}; int max = 0; int l = myArray.length; int index =0; int temp = 0; while (l>=0){ for (int i=0;i<l;i++){ if(max<=myArray[i]){ max=myArray[i]; index = i; } } temp = myArray[(l - 1)]; myArray[index] = temp; myArray[(l - 1)] = max; String s = " Iteration - " + l + " MAX INDEX = " + index + " temp = " + temp + " MAX = " + max; System.out.println(s); index = 0; max = 0; l = l-1; } for (int v : myArray){ System.out.print(v); } 

Displays only the sorting process, and the sorted array does not output

  Iteration - 7 MAX INDEX = 3 temp = 3 MAX = 8 Iteration - 6 MAX INDEX = 1 temp = 0 MAX = 7 Iteration - 5 MAX INDEX = 0 temp = 1 MAX = 5 Iteration - 4 MAX INDEX = 3 temp = 3 MAX = 3 Iteration - 3 MAX INDEX = 2 temp = 2 MAX = 2 Iteration - 2 MAX INDEX = 0 temp = 0 MAX = 1 Iteration - 1 MAX INDEX = 0 temp = 0 MAX = 0 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

http://ideone.com/RBjVNj

Your code crashes when accessing an array element with index -1 :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Ideone.main (Main.java:24)

 temp = myArray[(l - 1)]; 

When you correct this error, the output of the array will work almost normally.
Almost consists in the absence of spaces between the numbers.


Perhaps an error in the condition of the while loop and it needs to be changed to:

 while (l>0){ 

http://ideone.com/CbdmLl

But I can not guarantee, I am too lazy to deal with the sorting algorithm.

    Thanks for the help, corrected the condition in the while loop and corrected the output, with spaces

     int[] myArray = {5, 7, 2, 8, 1, 0, 3,6}; System.out.print("Input: "); for (int v : myArray){ System.out.print(v + " "); } System.out.println(); int max = 0; int l = myArray.length; int index =0; int temp = 0; while (l>0){ for (int i=0;i<l;i++){ if(max<=myArray[i]){ max=myArray[i]; index = i; } } temp = myArray[(l - 1)]; myArray[index] = temp; myArray[(l - 1)] = max; index = 0; max = 0; l = l-1; } System.out.print("Result: "); for (int v : myArray){ System.out.print(v + " "); }