Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.
The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200, 000 random lists) [Source: Wiki]
Although, it works better than Bubble Sort on average, worst case remains O(n2).
Â
CPP
// C++ implementation of Comb Sort #include <bits/stdc++.h> 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
Â
Time Complexity: The worst-case complexity of this algorithm is O(n2).
Auxiliary Space: O(1).
Please refer complete article on Comb Sort for more details!
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!