-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #65 from nishchay2517/pr1
Added code for odd-even sort
- Loading branch information
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
Computational_Algorithms/Sorting_Algorithms/odd_even_sort.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |