Caută
• oanaunciuleanu

# Shell Sort Algorithm in C++

Shell sort is a sorting algorithm that uses a gap between elements to compare the values. The gap between elements shrinks until is 0 and the array is sorted. This technique is based on Insertion Sort, but in shell sort we avoid shifting large interval of elements by using specific interval.

```// Shell Sort

#include <iostream>
using namespace std;

int shellSort(int arrayOfNumbers[], int numberOfElements)
{
// Set the first gap as half of the array, then divide it by 2
for (int gap = numberOfElements/2; gap > 0; gap /= 2)
{
// Insertion Sort for this gap
for (int i = gap; i < numberOfElements; i += 1)
{
int temp = arrayOfNumbers[i];

// Shift elements
int j;
for (j = i; j >= gap && arrayOfNumbers[j - gap] > temp; j -= gap)
{
arrayOfNumbers[j] = arrayOfNumbers[j - gap];
}
arrayOfNumbers[j] = temp;
}
}
return 0;
}
void printElementsOfArray(int arrayOfNumbers[], int numberOfElements)
{
for (int i = 0; i < numberOfElements; ++i)
{
cout << arrayOfNumbers[i] << " ";
}
cout << endl;
}

int main(void)
{
int arrayOfNumbers[] = {4, 7, 9, 3, 21, 18, 23, 15, 8, 17};
int numberOfElements = sizeof(arrayOfNumbers) / sizeof(arrayOfNumbers[0]);

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

75 afișare0 comentariu

## Postări recente

Afișează-le pe toate