Compile and Run this code and explain what it is doing. Can someone help break t
ID: 670304 • 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 BubbleSort(int numbers [])
{
for (int i = 0; i < 13; i++) {
System.out.print("Pass"+ (i+1) + "[");
for (int j = 1; j < (13-i); j++)
{
if (numbers [j-1] > numbers[j])
{
int temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
for (int j1 = 0; j1 < 13; j1++)
System.out.print(numbers[j1]+" ");
System.out.println("]");
}
System.out.println(" Bubble Sorting");
System.out.print("[");
for(int i=0; i<13; i++)
{
System.out.print(" " + numbers[i]);
}
System.out.println("]");
}
Explanation / Answer
void BubbleSort(int numbers [])
{
//this for loops for n times where n is the number of elements in array
for (int i = 0; i < 10; i++) {
System.out.print("Pass"+ (i+1) + "[");
//this for loop runs over the elements from the first one to the one which we are running on the outer loop for that j<10-i
for (int j = 1; j < (10-i); j++)
{
//here we compare the j-1th element and jth element if j-1 element is greater than jth element then we swap them both by this we sort up to the i elemnts
//if you want the descending order then just reverse the greater than to less than try for yourself
if (numbers [j-1] >numbers[j])
{
//simple swap between jth and j-1th element
int temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
//this one for printing the array at each outer iteration
for (int j1 = 0; j1 < 10; j1++)
System.out.print(numbers[j1]+" ");
System.out.println("]");
}
//this one for printing the sorted array
System.out.println(" Bubble Sorting");
System.out.print("[");
for(int i=0; i<10; 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.