In: Computer Science
Can you explain in details how this loop works?
int[] someNums = {90, 85, 65, 95, 75} ;
a = 1;
while(a < someNums.length) {
temp = someNums [a ];
b = a - 1 ;
while(b >= 0 && someNums[ b] >temp) {
someNums [b + 1] = someNums [ b];
--b;
}
someNums [b + 1] = temp ;
++a ; }
Given loop is sorting the elemets in someNums array.
Explanation.
1) outer loop is running from a=1 to (someNums.length - 1) i.e from 1 to last index of array someNums.
2) in each iteration of outer loop element at index a is being stored in temp and b is initialized to a-1
3) Inner loop is running until b is greater than equal to 0 and element at b index is greater than temp.
4) in each iteration of inner loop, element at index b is moved to one location ahead i.e it is creating empty space for the smaller element.
5) when the control comes out of inner loop, temp is being copied to empty space as it is correct position for it.
6) after one complete iteration of outer loop, element at index a is placed at correct position.
7) when the control comes out of inner loop array is sorted.
Below is the complete program with the output of screenshot.
public class Main
{
public static void main(String[] args) {
int[] someNums = {90, 85, 65, 95, 75} ;
int a = 1;
int temp,b;
while(a < someNums.length)
{
temp = someNums [a ];
b = a - 1 ;
while(b >= 0 && someNums[ b] >temp)
{
someNums [b + 1] = someNums [ b];
--b;
}
someNums [b + 1] = temp ;
++a ;
}
for(int i=0;i<someNums.length;i++)
{
System.out.println(someNums[i]);
}
}
}
Please upvote if u like answer otherwise comment for any doubt