diff --git a/OddEven Sort/c++/OddEvenSort-C++.cpp b/OddEven Sort/c++/OddEvenSort-C++.cpp new file mode 100644 index 0000000..15dcc28 --- /dev/null +++ b/OddEven Sort/c++/OddEvenSort-C++.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +void oddEvenSort(int arr[], int n) +{ + bool isSorted = false; + + while (!isSorted) + { + isSorted = true; + + for (int i = 1; i <= n - 2; i = i + 2) + { + if (arr[i] > arr[i + 1]) + { + swap(arr[i], arr[i + 1]); + isSorted = false; + } + } + + for (int i = 0; i <= n - 2; i = i + 2) + { + if (arr[i] > arr[i + 1]) + { + swap(arr[i], arr[i + 1]); + isSorted = false; + } + } + } + + return; +} + +void printArray(int arr[], int n) +{ + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + cout << "\n"; +} + +int main() +{ + int arr[] = {34, 2, 10, -9}; + int n = sizeof(arr) / sizeof(arr[0]); + + oddEvenSort(arr, n); + printArray(arr, n); + + return (0); +} \ No newline at end of file diff --git a/OddEven Sort/c++/OddEvenSort-C++.exe b/OddEven Sort/c++/OddEvenSort-C++.exe new file mode 100644 index 0000000..c3a993c Binary files /dev/null and b/OddEven Sort/c++/OddEvenSort-C++.exe differ diff --git a/OddEven Sort/c++/algorithmOddEvenSort-Cpp.txt b/OddEven Sort/c++/algorithmOddEvenSort-Cpp.txt new file mode 100644 index 0000000..347e19c --- /dev/null +++ b/OddEven Sort/c++/algorithmOddEvenSort-Cpp.txt @@ -0,0 +1,8 @@ +The algorithm for odd even sort in c++ is as follows:- +example: the array is {34, 2, 10, -9} +First, we consider array to be unsorted, +Then, we run a while loop which begins with considering array as sorted. It runs until array is not sorted. We intialize a +for loop for the elements at odd indices. If arr[i]>arr[i+1], we swap them. With each swap we set isSorted value to false. +A second for loop is initialized for elemnts at even indices. If arr[i]>arr[i+1], we swap them. With each swap we set isSorted +value to false. +This repeated swapping finally sorts the array, \ No newline at end of file