TheAlgorithms-C-Plus-Plus/sorting/CocktailSelectionSort.cpp

110 lines
2.1 KiB
C++
Raw Normal View History

//Returns Sorted elements after performing Cocktail Selection Sort
2019-08-21 10:10:08 +08:00
//It is a Sorting algorithm which chooses the minimum and maximum element in an array simultaneously,
//and swaps it with the lowest and highest available position iteratively or recursively
2019-08-21 10:10:08 +08:00
#include <iostream>
using namespace std;
//Iterative Version
2019-08-21 10:10:08 +08:00
void CocktailSelectionSort(vector<int> &vec, int low, int high)
{
2019-08-21 10:10:08 +08:00
while (low <= high)
{
2019-08-21 10:10:08 +08:00
int minimum = vec[low];
int minimumindex = low;
int maximum = vec[high];
int maximumindex = high;
2019-08-21 10:10:08 +08:00
for (int i = low; i <= high; i++)
{
2019-08-21 10:10:08 +08:00
if (vec[i] >= maximum)
{
maximum = vec[i];
maximumindex = i;
}
if (vec[i] <= minimum)
{
minimum = vec[i];
minimumindex = i;
}
}
2019-08-21 10:10:08 +08:00
if (low != maximumindex || high != minimumindex)
{
2019-08-21 10:10:08 +08:00
swap(vec[low], vec[minimumindex]);
swap(vec[high], vec[maximumindex]);
}
2019-08-21 10:10:08 +08:00
else
{
swap(vec[low], vec[high]);
}
low++;
high--;
}
}
//Recursive Version
2019-08-21 10:10:08 +08:00
void CocktailSelectionSort(vector<int> &vec, int low, int high)
{
2019-08-21 10:10:08 +08:00
if (low >= high)
return;
int minimum = vec[low];
int minimumindex = low;
int maximum = vec[high];
int maximumindex = high;
for (int i = low; i <= high; i++)
{
2019-08-21 10:10:08 +08:00
if (vec[i] >= maximum)
{
2019-08-21 10:10:08 +08:00
maximum = vec[i];
maximumindex = i;
}
2019-08-21 10:10:08 +08:00
if (vec[i] <= minimum)
{
2019-08-21 10:10:08 +08:00
minimum = vec[i];
minimumindex = i;
}
}
2019-08-21 10:10:08 +08:00
if (low != maximumindex || high != minimumindex)
{
2019-08-21 10:10:08 +08:00
swap(vec[low], vec[minimumindex]);
swap(vec[high], vec[maximumindex]);
}
else
{
2019-08-21 10:10:08 +08:00
swap(vec[low], vec[high]);
}
2019-08-21 10:10:08 +08:00
CocktailSelectionSort(vec, low + 1, high - 1);
}
//main function, select any one of iterative or recursive version
int main()
{
2019-08-21 10:10:08 +08:00
int n;
cout << "Enter number of elements\n";
cin >> n;
std::vector<int> v(n);
cout << "Enter all the elements\n";
for (int i = 0; i < n; ++i)
{
cin >> v[i];
}
2019-08-21 10:10:08 +08:00
CocktailSelectionSort(v, 0, n - 1);
cout << "Sorted elements are\n";
for (int i = 0; i < n; ++i)
{
cout << v[i] << " ";
}
return 0;
}