Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added code for odd-even sort #65

Merged
merged 2 commits into from
Oct 29, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Computational_Algorithms/Sorting_Algorithms/odd_even_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include<bits/stdc++.h>
using namespace std;
void odd_even_sort(vector<int> &arr , int n){
bool is_sorted = false; //initialised a flag to track if array is sorted or not.

while (!is_sorted)
{
is_sorted = true; //make flag as sorted initially
for (int i = 0; i <= n-2; i = i+2) //loop over even elements
{
if(arr[i] >arr[i+1]){
swap(arr[i],arr[i+1]); //if next element is smaller than swap the elements
is_sorted = false;//mark the flag as unsorted as we have swapped the elements
}
}
for (int i = 1; i <= n-2; i = i+2) //loops over odd elements
{
if(arr[i] >arr[i+1]){
swap(arr[i],arr[i+1]);//if next element is smaller than swap the elements
is_sorted = false; //mark the flag as unsorted as we have swapped the elements
}
}
}
}
int main()
{
vector<int> arr ={5 ,2 ,6 ,78 ,8};
odd_even_sort(arr , arr.size());
for(auto ele : arr){
cout<<ele<<endl;
}
return 0;
}