Skip to content
This repository was archived by the owner on Oct 29, 2020. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions CPP/combSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// 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 n; //number of elements in array
cout<<"Nubers of elements: ";
cin>>n;
int arr[n];
cout<<"Enter all elements seprated by space:";
for(int i=0;i<n;cin>>arr[i],i++);

combSort(arr, n);

printf("Sorted array: \n");
for (int i=0; i<n; i++)
printf("%d ", arr[i]);

return 0;
}