Home > Software engineering >  Attempt at sorting array in ascending order [closed]
Attempt at sorting array in ascending order [closed]

Time:09-24

For some reason the array does not sort correctly, i have looked it up and found code that uses this same method but what i wrote for some reason doesn't work could anybody experienced please tell me why?

class AscendingOrderSort {

   static int length;

     static void PrintArray(int array[]){
       for (int i=0;i<length;i  ){
        System.out.print(array[i]   " ");
       }
        System.out.println("<<< SORTED ARRAY");
     }
   
     static void SortArray(int array[]){
       int temp = 0;

      for(int i=0;i<length;i  )
       for(int j=i 1;i<length;i  ){
        {
         if (array[i]>array[j]){
           temp = array[i];
           array[i] = array[j];
           array[j] = temp;
         }
       }
     }
    }

    public static void main(String args[]){
      int array[] = {
        1789, 2035, 1899, 1456 
        };
        length = array.length;

        SortArray(array);

        PrintArray(array);
    }
}

output: 1789 2035 1899 1456 <<< SORTED ARRAY

CodePudding user response:

Look like you did a copy paste , you are incrementing i in the second loop

for(int i=0;i<length;i  )
   for(int j=i 1;i<length;i  )

instead of

for(int i=0;i<length;i  )
        for(int j=i 1;j<length;j  )
  •  Tags:  
  • java
  • Related