Skip to content
This repository has been archived by the owner on Dec 19, 2022. It is now read-only.

Added sorting technique #426

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
66 changes: 66 additions & 0 deletions C++/OddEvenSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#include <bits/stdc++.h>
using namespace std;

// Perform bubbleSort on every alternating element starting from 'start'
// Returns true if the alternating elements are sorted already, otherwise false.
bool bubbleSort(int arr[], int n, int start)
{
bool isSorted = true;

for (int i = start; i <= n - 2; i = i + 2) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
isSorted = false;
}
}

return isSorted;
}

void oddEvenSort(int arr[], int n)
{
bool isSorted = false;

while (!isSorted) {
isSorted = true;

// Perform Bubble sort on odd indexed element,
// which is same as performing bubble sort on every
// alternating element starting from 1st element.
isSorted = bubbleSort(arr, n, 1);

// Perform Bubble sort on even indexed element,
// which is same as performing bubble sort on every
// alternating element starting from 0th element.
isSorted = bubbleSort(arr, n, 0);
}

}

void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\n";
}

// Driver program.
int main()
{
int n = 6, maxElement = 100;
int arr[n];

for(int i = 0; i < n; i++) {
arr[i] = rand() % maxElement;
}

cout << "Before sorting: " << endl;
printArray(arr, n);

oddEvenSort(arr, n);

cout << "After sorting: " << endl;
printArray(arr, n);

return 0;
}