梳状排序主要是对冒泡排序的改进。冒泡排序始终会比较相邻的值。因此,所有反演都将一一删除。通过使用大小大于1的间隙,梳状排序在Bubble排序上有所改进。该间隙以一个较大的值开始,并在每次迭代中缩小1.3倍,直到达到值1。因此,梳状排序使用一个来消除一个以上的反转计数交换并比Bublle Sort表现更好。
根据经验发现,收缩因子为1.3(通过对200,000个随机列表进行Combsort测试)[来源:Wiki]
尽管它的平均效果优于冒泡排序,但最差的情况仍然是O(n 2 )。
// Java program for implementation of Comb Sort
class CombSort {
// To find gap between elements
int getNextGap(int gap)
{
// Shrink gap by Shrink factor
gap = (gap * 10) / 13;
if (gap < 1)
return 1;
return gap;
}
// Function to sort arr[] using Comb Sort
void sort(int arr[])
{
int n = arr.length;
// initialize gap
int gap = n;
// Initialize swapped as true to make sure that
// loop runs
boolean swapped = true;
// Keep running while gap is more than 1 and last
// iteration caused a swap
while (gap != 1 || swapped == true) {
// Find next gap
gap = getNextGap(gap);
// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;
// Compare all elements with current gap
for (int i = 0; i < n - gap; i++) {
if (arr[i] > arr[i + gap]) {
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i + gap];
arr[i + gap] = temp;
// Set swapped
swapped = true;
}
}
}
}
// Driver method
public static void main(String args[])
{
CombSort ob = new CombSort();
int arr[] = { 8, 4, 1, 56, 3, -44, 23, -6, 28, 0 };
ob.sort(arr);
System.out.println("sorted array");
for (int i = 0; i < arr.length; ++i)
System.out.print(arr[i] + " ");
}
}
/* This code is contributed by Rajat Mishra */
输出:
sorted array
-44 -6 0 1 3 4 8 23 28 56
请参阅梳状排序的完整文章以了解更多详细信息!