Solution Review: Sorting an Array
In this review, solution of the challenge 'Sorting an Array' from the previous lesson is provided.
We'll cover the following...
We'll cover the following...
Solution
Java
class SortArr {public static void sortAsc(int[] arr) {int temp = 0; //a variable to store temporary value while swappingfor (int i = 0; i < arr.length-1; i++) //for loop to hold the current element to be compared{for (int j = i + 1; j < arr.length; j++) //for loop to iterate over the other elements{ //to get them compared with the current elementif (arr[i] > arr[j]) //if any of the higher index element is smaller than{ //the current elementtemp = arr[i]; //store the current element to temparr[i] = arr[j]; //store the smaller element to the lower index positionarr[j] = temp; //store the current element to greater index position}}}}public static void main( String args[] ) {int array[] = {56, 9, 45, 108, 567, 21};System.out.println( "Array values before sorting:" );for (int i =0 ; i < array.length; i++){System.out.print(array[i]+ " ");}System.out.println();sortAsc(array);System.out.println( "Array values after sorting:" );for (int i =0 ; i < array.length; i++){System.out.print(array[i]+ " ");}}}
How does the above code work?
In the above code, we have implemented nested for
loops and an int
variable named temp to store a value which is going to be swapped.
- Line 5 - 8:
The control variable i,
from the outer for
loop is used as an index ...