Athul Antony NP Athul Antony NP - 1 year ago 63
Java Question

Array Sorting getting error

class arr{
//array sorting to find maximum value
public static void main(String[]args){
int[] array={1,6,4,5,2};
int n;
int i,j;
for( i=0;i<(array.length*2);i++){
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
}
System.out.println(array[array.length]);
}


}

>
Can anyone tell me why i am getting runtime error and this sorting method will work or not?




Answer Source

Dont reinvent the wheel.., you are able to use arrays, so then use the array help class too... :-)

public static void main(String[] args) {

    final int[] array = { 1, 6, 4, 5, 2 };
    System.out.println("Array before sort " + Arrays.toString(array));
    Arrays.sort(array);
    System.out.println("Array before sort " + Arrays.toString(array));
}