Implement a bubble sort as a static method with the signature given below that t
ID: 3772561 • Letter: I
Question
Implement a bubble sort as a static method with the signature given below that takes
an array as input and sorts this array in ascending order (i.e., smallest to largest) and
in-place (i.e., without copying the items to a new array). You may use pseudocode, so
long as it is at the same level of detail as Java and is clear and unambiguous. You may
assume the existence of a swap(int[] array, int a, int b) function to assist in
your work, where a and b are the indices of elements in array that you wish to swap.
Here is the signature: public static void mySort(int[] toSort)
Explanation / Answer
public static void mySort( int [ ] toSort )
{
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < toSort.length -1; j++ )
{
if ( toSort[ j ] < toSort[j+1] ) // change to > for ascending sort
{
temp = toSort[ j ]; //swap elements
toSort[ j ] = toSort[ j+1 ];
toSort[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.