A java Problem. There is a variation of the bubble sort algorithm called a gap s
ID: 3764224 • Letter: A
Question
A java Problem.
There is a variation of the bubble sort algorithm called a gap sort that rather than comparing neighboring elements each time through the list, compares elements that are i positions apart, where i is an integer less than n. For example, the first element would be compared to the (i + 1) element, the second element be compared to the (i + 2) element, the nth element would be compared to the (n - i) element, and so on. A single iteration is completed when all of the elements that can be compared have been compared. On the next iteration, i is reduced by some number greater than 1, and the process continues until i is less than 1. Implement a gap sort.
Explanation / Answer
public static void bubbleSort (Comparable[] data, int maxlength)
{
int position, scan;
Comparable temp;
for (position = maxlength; position >= 1; position--)
{
for (scan = 0; scan <= position – 1; scan++)
{
if (data[scan].compareto(data[scan+1]) > 0)
{
// Swap the values
temp = data[scan];
data[scan] = data[scan + 1];
data[scan + 1] = temp;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.