TheAlgorithms-C-Plus-Plus/Sorting/OddEven Sort.cpp

63 lines
890 B
C++
Raw Normal View History

/* C++ implementation Odd Even Sort */
2019-02-10 13:50:09 +08:00
#include <iostream>
#include <vector>
2019-02-10 13:50:09 +08:00
using namespace std;
2019-02-10 13:50:09 +08:00
void oddEven(vector<int> &arr, int size)
{
bool sorted = false;
2019-02-10 13:50:09 +08:00
while( ! sorted )
{
sorted = true;
for(int i = 1; i < size-1; i += 2)//Odd
{
if(arr[i] > arr[i+1])
{
2019-02-10 13:50:09 +08:00
swap(arr[i], arr[i+1]);
sorted = false;
}
}
for(int i = 0; i < size-1; i += 2)//Even
{
if(arr[i] > arr[i+1])
{
2019-02-10 13:50:09 +08:00
swap(arr[i], arr[i+1]);
sorted = false;
}
}
}
}
2019-02-10 13:50:09 +08:00
void show(vector<int> A, int size)
{
int i;
for (i = 0; i < size; i++)
2019-02-10 13:50:09 +08:00
cout << A[i] << "\n";
}
int main()
{
2019-02-10 13:50:09 +08:00
int size, temp;
cout << "\nEnter the number of elements : ";
cin >> size;
2019-02-10 13:50:09 +08:00
vector<int> arr;
2019-02-10 13:50:09 +08:00
cout<<"\nEnter the unsorted elements : \n";
for (int i = 0; i < size; ++i)
{
2019-02-10 13:50:09 +08:00
cin >> temp;
arr.push_back(temp);
}
oddEven(arr, size);
cout<<"Sorted array\n";
show(arr, size);
return 0;
}