我遇到了问题,需要你的指导。基本上我设法创建这个冒泡排序方法。我如何将其修改为Gap Sort,而不是每次通过列表比较相邻元素,比较某些数字(i)位置分开的元素,其中(i)是小于n的整数。例如,第一个元素将与(i + 1)元素,第二个元素与(i + 2)元素,第n个元素与(ni)元素等进行比较。当所有元素完成时,单个迭代完成可比较,已被比较。在下一次迭代中,i减少大于1的某个数,并且该过程继续,直到i小于1
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;
}
}
}
}
答案 0 :(得分:1)
此代码(位于http://www.daniweb.com/software-development/java/threads/238791/gap-sort上)可能会对您有所帮助:
public static void gapSort (Comparable [] data, int size) {
int index;
int gap, top;
Comparable temp;
boolean exchanged;
double SF = 1.3;
gap = size;
do {
exchanged = false;
gap = (int) (gap / SF);
if (gap == 0){
gap = 1;
}
for (index = 1; index <= size - gap; index++) {
if (data [index].compareTo(data [index + gap]) > 0) {
temp = data [index];
data [index] = data [index + gap];
data [index + gap] = temp;
exchanged = true;
}
}
} while (exchanged || gap > 1);
}
请记住,对实现Comparable
接口的对象数组进行排序的最简单方法通常是Arrays.Sort()