Compile and Run this code and explain what it is doing. Can someone help break t
ID: 670305 • Letter: C
Question
Compile and Run this code and explain what it is doing. Can someone help break this down and explain what this code is actually doing? Please and Thank You
void InsertionSort(int numbers[])
{
for (int i = 1; 1 < 13; i++){
System.out.print("Process"+i+"[ ");
int j = i;
int B = numbers[i];
while ((j > 0) && (numbers[j-1] > B )){
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = B;
for(int j1 = 0; j1 <13; j1++)
System.out.print(numbers[j1]+" ");
System.out.println("]");
}
System.out.println(" After Insertion Sorting");
System.out.print("[");
for (int i=0; i<13;i++)
{
System.out.print(" " + numbers[i]);
}
System.out.println("]");
}
Explanation / Answer
// Function InsertionSort defined with 1 array having 13 elements as parameter
void InsertionSort(int numbers[]){
// loop through the array 13 times(because 13 elements are there)
for(int i = 1; i < 13; i++){
// Print the loop number
System.out.print("Process" + i + "[ ");
// set j = i
int j = i;
// store the element at ith index in B
int B = numbers[i];
// find the appropriate position for b in the first i places
while((j > 0) && (numbers[j - 1] > B)){
numbers[j] = numbers[j-1];
j--;
}
// j is the required position
// Now we set the element at jth position as B
numbers[j] = B;
// print the array in each step
for(int j1 = 0; j1 <13; j1++)
System.out.print(numbers[j1]+" ");
System.out.println("]");
}
// print the final array after the loop ends
System.out.println(" After Insertion Sorting");
System.out.print("[");
for (int i=0; i<13;i++){
System.out.print(" " + numbers[i]);
}
System.out.println("]");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.