TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
cocktail_selection_sort.cpp
1// Returns Sorted elements after performing Cocktail Selection Sort
2// It is a Sorting algorithm which chooses the minimum and maximum element in an
3// array simultaneously, and swaps it with the lowest and highest available
4// position iteratively or recursively
5
6#include <algorithm>
7#include <iostream>
8#include <vector>
9
10// Iterative Version
11
12void CocktailSelectionSort(std::vector<int> *vec, int low, int high) {
13 while (low <= high) {
14 int minimum = (*vec)[low];
15 int minimumindex = low;
16 int maximum = (*vec)[high];
17 int maximumindex = high;
18
19 for (int i = low; i <= high; i++) {
20 if ((*vec)[i] >= maximum) {
21 maximum = (*vec)[i];
22 maximumindex = i;
23 }
24 if ((*vec)[i] <= minimum) {
25 minimum = (*vec)[i];
26 minimumindex = i;
27 }
28 }
29 if (low != maximumindex || high != minimumindex) {
30 std::swap((*vec)[low], (*vec)[minimumindex]);
31 std::swap((*vec)[high], (*vec)[maximumindex]);
32 } else {
33 std::swap((*vec)[low], (*vec)[high]);
34 }
35
36 low++;
37 high--;
38 }
39}
40
41// Recursive Version
42
43void CocktailSelectionSort_v2(std::vector<int> *vec, int low, int high) {
44 if (low >= high)
45 return;
46
47 int minimum = (*vec)[low];
48 int minimumindex = low;
49 int maximum = (*vec)[high];
50 int maximumindex = high;
51
52 for (int i = low; i <= high; i++) {
53 if ((*vec)[i] >= maximum) {
54 maximum = (*vec)[i];
55 maximumindex = i;
56 }
57 if ((*vec)[i] <= minimum) {
58 minimum = (*vec)[i];
59 minimumindex = i;
60 }
61 }
62 if (low != maximumindex || high != minimumindex) {
63 std::swap((*vec)[low], (*vec)[minimumindex]);
64 std::swap((*vec)[high], (*vec)[maximumindex]);
65 } else {
66 std::swap((*vec)[low], (*vec)[high]);
67 }
68
69 CocktailSelectionSort(vec, low + 1, high - 1);
70}
71
72// main function, select any one of iterative or recursive version
73
74int main() {
75 int n;
76 std::cout << "Enter number of elements\n";
77 std::cin >> n;
78 std::vector<int> v(n);
79 std::cout << "Enter all the elements\n";
80 for (int i = 0; i < n; ++i) {
81 std::cin >> v[i];
82 }
83
84 int method;
85 std::cout << "Enter method: \n\t0: iterative\n\t1: recursive:\t";
86 std::cin >> method;
87
88 if (method == 0) {
89 CocktailSelectionSort(&v, 0, n - 1);
90 } else if (method == 1) {
91 CocktailSelectionSort_v2(&v, 0, n - 1);
92 } else {
93 std::cerr << "Unknown method" << std::endl;
94 return -1;
95 }
96 std::cout << "Sorted elements are\n";
97 for (int i = 0; i < n; ++i) {
98 std::cout << v[i] << " ";
99 }
100
101 return 0;
102}
int main()
Main function.