COMB SORT
Comb Sort is the advance form of Bubble Sort. Bubble Sort compares all the adjacent values while comb sort removes all the turtle values or small values near the end of the list.
Factors affecting comb sort are:
- It improves on bubble sort by using gap of size more than 1.
- Gap starts with large value and shrinks by the factor of 1.3.
- Gap shrinks till value reaches 1.
Complexity
Algorithm | Complexity |
---|---|
Worst Case Complexity | O(n2) |
Best Case Complexity | θ(n log n) |
Average Case Complexity | Ω(n2/2p) where p is number of increments. |
Worst Case Space Complexity | O(1) |
Algorithm
- STEP 1 START
- STEP 2 Calculate the gap value if gap value==1 goto step 5 else goto step 3
- STEP 3 Iterate over data set and compare each item with gap item then goto step 4.
- STEP 4 Swap the element if require else goto step 2
- STEP 5 Print the sorted array.
- STEP 6 STOP
Program
- #include <stdio.h>
- #include <stdlib.h>
- int newgap(int gap)
- {
- gap = (gap * 10) / 13;
- if (gap == 9 || gap == 10)
- gap = 11;
- if (gap < 1)
- gap = 1;
- return gap;
- }
- void combsort(int a[], int aSize)
- {
- int gap = aSize;
- int temp, i;
- for (;;)
- {
- gap = newgap(gap);
- int swapped = 0;
- for (i = 0; i < aSize - gap; i++)
- {
- int j = i + gap;
- if (a[i] > a[j])
- {
- temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- swapped = 1;
- }
- }
- if (gap == 1 && !swapped)
- break;
- }
- }
- int main ()
- {
- int n, i;
- int *a;
- printf("Please insert the number of elements to be sorted: ");
- scanf("%d", &n); // The total number of elements
- a = (int *)calloc(n, sizeof(int));
- for (i = 0;i< n;i++)
- {
- printf("Input element %d :", i);
- scanf("%d", &a[i]); // Adding the elements to the array
- }
- printf("unsorted list"); // Displaying the unsorted array
- for(i = 0;i < n;i++)
- {
- printf("%d", a[i]);
- }
- combsort(a, n);
- printf("Sorted list:\n"); // Display the sorted array
- for(i = 0;i < n;i++)
- {
- printf("%d ", (a[i]));
- }
- return 0;
- }