Compile and Run this code and explain what it is doing. Can someone help break t
ID: 670306 • 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 ShellSort(int numbers[])
{
int inner, outer, temp;
int h = 1;
while (h > 0){
for (outer = h; outer < 13; outer++){
System.out.print("Pass2"+outer+"[");
temp = numbers[outer];
inner = outer;
while (inner > h - 1 && numbers[inner - h] >= temp)
{
numbers[inner] = numbers[inner - h];
inner -= h;
}
numbers[inner] = temp;
for(int j1 = 0; j1 <13; j1++)
System.out.print(numbers[j1]+" ");
System.out.println("]");
}
h = (h-1) / 3;
}
System.out.println(" Shell Sorting");
System.out.print("[");
for(int i=0; i<13; i++){
System.out.print(" " + numbers[i]);
}
System.out.println("]");
}
Explanation / Answer
Initial array : [96, 68, 7, 76, 24, 95, 10, 27, 77, 46, 94, 19, 17, ]
----------------------- Output of the compiled programme --------------------------------
Pass21[68 96 7 76 24 95 10 27 77 46 94 19 17 ]
Pass22[7 68 96 76 24 95 10 27 77 46 94 19 17 ]
Pass23[7 68 76 96 24 95 10 27 77 46 94 19 17 ]
Pass24[7 24 68 76 96 95 10 27 77 46 94 19 17 ]
Pass25[7 24 68 76 95 96 10 27 77 46 94 19 17 ]
Pass26[7 10 24 68 76 95 96 27 77 46 94 19 17 ]
Pass27[7 10 24 27 68 76 95 96 77 46 94 19 17 ]
Pass28[7 10 24 27 68 76 77 95 96 46 94 19 17 ]
Pass29[7 10 24 27 46 68 76 77 95 96 94 19 17 ]
Pass210[7 10 24 27 46 68 76 77 94 95 96 19 17 ]
Pass211[7 10 19 24 27 46 68 76 77 94 95 96 17 ]
Pass212[7 10 17 19 24 27 46 68 76 77 94 95 96 ]
Shell Sorting
[ 7 10 17 19 24 27 46 68 76 77 94 95 96]
//What its doing
By defining h the algorthm deciding from where the sorting has to be started. Here h = 1, means comparasion of array elements start first with 2nd element in the array.
First it comparing elemnt 1 and element 2 and arranging them in ascending order.
In 2nd pass, its comparing element 3 and ordering elements 1,2,3 in ascending order and so on.
If you select h =5, then it compares 5th element with 6th element onwards and sorts the lements from 5th to 13 th.
In the next step h = 5-1/3 = 1, now sorts elements 1 to 5, by comparing elements with other elements.
Its trying findout the correct location for each element.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.