Skip to content

Commit

Permalink
Merge pull request #65 from nishchay2517/pr1
Browse files Browse the repository at this point in the history
Added code for odd-even sort
  • Loading branch information
metabiswadeep authored Oct 29, 2023
2 parents 2dcfaf7 + 5ce3b06 commit 7a7891a
Showing 1 changed file with 33 additions and 0 deletions.
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;
}

0 comments on commit 7a7891a

Please sign in to comment.