top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Comb Sort Algorithm in C++





The Comb Sort Algorithm is very similar to Bubble Sort. It is used to sort an array, by comparing values. The difference is that Count Sort uses different gaps between the compared elements. This gap in the first iteration is large, and then it gets divided by 1.3 at every iteration, until it reaches 1. The elements are compared to each other, and if the elements on the right is smaller than the one on the left, then they are swapped.



// Comb sort

#include <iostream>
using namespace std;

void combSort(int arrayOfNumbers[], int numberOfElements)
{
    int gap = numberOfElements;
    bool continueSort = true;
    while(gap != 1 || continueSort == true)
    {
        // Change the gap at every loop
        gap = gap / 1.3;
        if(gap < 1)
        {
            gap = 1;
        }

      continueSort = false;

        // Compare the values separated by the gap
        for(int i = 0; i < numberOfElements - gap; i++)
        {
            if(arrayOfNumbers[i] > arrayOfNumbers[i + gap])
            {
                swap(arrayOfNumbers[i], arrayOfNumbers[i + gap]);
                continueSort = true;
            }
        }
    }
}
void printElementsOfArray(int arrayOfNumbers[], int numberOfElements)
{
    for (int i = 0; i < numberOfElements; i++)
    {
        cout << arrayOfNumbers[i] << " ";
    }
    cout << endl;
}

int main()
{
    int arrayOfNumbers[] = {1, 15, 9, 6, 17, 99, 48, 30, 61, 21};
    int numberOfElements = sizeof(arrayOfNumbers) / sizeof(arrayOfNumbers[0]);
    combSort(arrayOfNumbers, numberOfElements);

    cout<<"The sorted array is: \n";
    printElementsOfArray(arrayOfNumbers, numberOfElements);
    return 0;
}

135 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page