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

62 lines
909 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-08-21 10:10:08 +08:00
while (!sorted)
{
sorted = true;
2019-08-21 10:10:08 +08:00
for (int i = 1; i < size - 1; i += 2) //Odd
{
2019-08-21 10:10:08 +08:00
if (arr[i] > arr[i + 1])
{
2019-08-21 10:10:08 +08:00
swap(arr[i], arr[i + 1]);
sorted = false;
}
}
2019-08-21 10:10:08 +08:00
for (int i = 0; i < size - 1; i += 2) //Even
{
2019-08-21 10:10:08 +08:00
if (arr[i] > arr[i + 1])
{
2019-08-21 10:10:08 +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-08-21 10:10:08 +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);
2019-08-21 10:10:08 +08:00
cout << "Sorted array\n";
show(arr, size);
return 0;
}