Tutorialspoint

1 Answer
Jai Janardhan

The basic idea of comb sort and the bubble sort is same. In other words, comb sort is an improvement on the bubble sort. In the bubble sorting technique, the items are compared with the next item in each phase. But for the comb sort, the items are sorted in a specific gap. After completing each phase, the gap is decreased. The decreasing factor or the shrink factor for this sort is 1.3. It means that after completing each phase the gap is divided by 1.3.

The complexity of Comb Sort Technique

  1. Time Complexity: O(n log n) for the best case. O(n^2/2^p) (p is a number of increment) for average case and O(n^2) for the worst case.
  2. Space Complexity: O(1)

Input and Output

Input:
A list of unsorted data: 108 96 23 74 12 56 85 42 13 47
Output:
Array before Sorting: 108 96 23 74 12 56 85 42 13 47
Array after Sorting: 12 13 23 42 47 56 74 85 96 108

Algorithm

CombSort(array, size)

Input: An array of data, and the total number in the array

Output: The sorted Array

Begin
   gap := size
   flag := true
   while the gap ≠ 1 OR flag = true do
      gap = floor(gap/1.3) //the the floor value after division
      if gap < 1 then
         gap := 1
      flag = false

      for i := 0 to size – gap -1 do
         if array[i] > array[i+gap] then
            swap array[i] with array[i+gap]
            flag = true;
      done
   done
End

Source Code (C++)

#include<iostream>
#include<algorithm>
using namespace std;

void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}

void combSort(int *array, int size) {
   int gap = size; //initialize gap size with size of array
   bool flag = true;

   while(gap != 1 || flag == true) {
      gap = (gap*10)/13; //minimize gap by shrink factor
      if(gap<1)
         gap = 1;
      flag = false;

      for(int i = 0; i<size-gap; i++) { //compare elements with gap
         if(array[i] > array[i+gap]) {
            swap(array[i], array[i+gap]);
            flag = true;
         }
      }
   }
}

int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n]; //create an array with given number of elements
   cout << "Enter elements:" << endl;

   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }

   cout << "Array before Sorting: ";
   display(arr, n);
   combSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}

Output

Enter the number of elements: 10
Enter elements:
108 96 23 74 12 56 85 42 13 47
Array before Sorting: 108 96 23 74 12 56 85 42 13 47
Array after Sorting: 12 13 23 42 47 56 74 85 96 108
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.