Skip to content

Commit fa474f1

Browse files
Cocltail Selection Sort
1 parent 05bd7a9 commit fa474f1

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

cocltail_selsction_sort.cpp

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

0 commit comments

Comments
 (0)