The simplest sorting algorithm is not bubble sort or insertion sort but known as stupid sort aka gnome sort. The time complexity is like a bubble sort. However, the code base size is much smaller. Possibly it offers the smallest code base size in the domain of the sorting algorithm.
The details can be found on Wikipedia.
Here goes the code:
void gnomeSort(std::vector<int>& data)
{
int pos = 0;
while (pos < data.size())
{
if (pos == 0 or data[pos] >= data[pos - 1])
pos += 1;
else
{
std::swap(data[pos], data[pos - 1]);
pos -= 1;
}
}
}
{
int pos = 0;
while (pos < data.size())
{
if (pos == 0 or data[pos] >= data[pos - 1])
pos += 1;
else
{
std::swap(data[pos], data[pos - 1]);
pos -= 1;
}
}
}
int main()
{
{
std::vector<int> v4 = { 10, 0, 2, 33, 5, 77, 8, 19, 1, 7 };
gnomeSort(v4);
for (auto i: v4)
std::cout << i << " ";
}
Happy sorting...
Comments