From facd742c19ae93528e7f991ff27991051088fad7 Mon Sep 17 00:00:00 2001 From: PARISOT paul andrea Date: Mon, 16 Apr 2018 17:13:01 +0200 Subject: [PATCH] Implementation of the OddEven sorting algorithm --- Sorting/OddEven Sort.cpp | 68 ++++++++++++++++++++++++++++++++++++++++ Sorting/OddEven_Sort.cpp | 68 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 Sorting/OddEven Sort.cpp create mode 100644 Sorting/OddEven_Sort.cpp diff --git a/Sorting/OddEven Sort.cpp b/Sorting/OddEven Sort.cpp new file mode 100644 index 000000000..790d391a5 --- /dev/null +++ b/Sorting/OddEven Sort.cpp @@ -0,0 +1,68 @@ +/* C++ implementation Odd Even Sort */ +#include +using namespace std; + +void switchElmts(int arr[], int i, int j) +{ + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +void oddEven(int arr[], int size) +{ + bool sorted = false; + while(!sorted) + { + sorted = true; + for(int i = 1; i < size-1; i += 2)//Odd + { + if(arr[i] > arr[i+1]) + { + switchElmts(arr,i,i+1); + sorted = false; + } + } + + for(int i = 0; i < size-1; i += 2)//Even + { + if(arr[i] > arr[i+1]) + { + switchElmts(arr,i,i+1); + sorted = false; + } + } + } +} + +void show(int A[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout<>size; + + int arr[size]; + + cout<<"\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) + { + cout<<"\n"; + cin>>arr[i]; + } + + oddEven(arr, size); + + cout<<"Sorted array\n"; + show(arr, size); + return 0; +} diff --git a/Sorting/OddEven_Sort.cpp b/Sorting/OddEven_Sort.cpp new file mode 100644 index 000000000..790d391a5 --- /dev/null +++ b/Sorting/OddEven_Sort.cpp @@ -0,0 +1,68 @@ +/* C++ implementation Odd Even Sort */ +#include +using namespace std; + +void switchElmts(int arr[], int i, int j) +{ + int tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +void oddEven(int arr[], int size) +{ + bool sorted = false; + while(!sorted) + { + sorted = true; + for(int i = 1; i < size-1; i += 2)//Odd + { + if(arr[i] > arr[i+1]) + { + switchElmts(arr,i,i+1); + sorted = false; + } + } + + for(int i = 0; i < size-1; i += 2)//Even + { + if(arr[i] > arr[i+1]) + { + switchElmts(arr,i,i+1); + sorted = false; + } + } + } +} + +void show(int A[], int size) +{ + int i; + for (i = 0; i < size; i++) + cout<>size; + + int arr[size]; + + cout<<"\nEnter the unsorted elements : "; + + for (int i = 0; i < size; ++i) + { + cout<<"\n"; + cin>>arr[i]; + } + + oddEven(arr, size); + + cout<<"Sorted array\n"; + show(arr, size); + return 0; +}