📜  梳齿排序的C ++程序

📅  最后修改于: 2021-05-31 20:55:41             🧑  作者: Mango

梳状排序主要是对冒泡排序的改进。冒泡排序始终会比较相邻的值。因此,所有反演都将一一删除。通过使用大小大于1的间隙,梳状排序在Bubble排序上有所改进。该间隙从一个大值开始,并在每次迭代中缩小1.3倍,直到达到值1。因此,梳状排序用一个来消除一个以上的反转计数交换并比Bublle Sort表现更好。

根据经验发现,收缩因子为1.3(通过对200,000个随机列表进行Combsort测试)[来源:Wiki]

尽管它的平均效果优于冒泡排序,但最差的情况仍然是O(n 2 )。

// C++ implementation of Comb Sort
#include 
using namespace std;
  
// 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 a[0..n-1] using Comb Sort
void combSort(int a[], int n)
{
    // Initialize gap
    int gap = n;
  
    // Initialize swapped as true to make sure that
    // loop runs
    bool 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 (a[i] > a[i + gap]) {
                swap(a[i], a[i + gap]);
                swapped = true;
            }
        }
    }
}
  
// Driver program
int main()
{
    int a[] = { 8, 4, 1, 56, 3, -44, 23, -6, 28, 0 };
    int n = sizeof(a) / sizeof(a[0]);
  
    combSort(a, n);
  
    printf("Sorted array: \n");
    for (int i = 0; i < n; i++)
        printf("%d ", a[i]);
  
    return 0;
}
输出:
Sorted array: 
-44 -6 0 1 3 4 8 23 28 56

请参阅梳状排序的完整文章以了解更多详细信息!

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”