Created
February 26, 2021 23:45
-
-
Save HassanElDesouky/70628b2d4e685db433462b00933b4fbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <thread> | |
#include <chrono> | |
#include <algorithm> | |
using namespace std; | |
using namespace std::chrono; | |
int SIZE = 10; | |
void CountingSort(int* array) { | |
vector<int> arr; | |
for (int i = 0; i < SIZE/2; ++i) arr.push_back(array[i]); | |
int max = *max_element(arr.begin(), arr.end()); | |
int min = *min_element(arr.begin(), arr.end()); | |
int range = max - min + 1; | |
vector<int> count(range), output(arr.size()); | |
for (int i = 0; i < arr.size(); i++) | |
count[arr[i] - min]++; | |
for (int i = 1; i < count.size(); i++) | |
count[i] += count[i - 1]; | |
for (int i = arr.size() - 1; i >= 0; i--) { | |
output[count[arr[i] - min] - 1] = arr[i]; | |
count[arr[i] - min]--; | |
} | |
for (int i = 0; i < arr.size(); i++) | |
array[i] = output[i]; | |
} | |
void printArray(vector<int>& array); | |
void printArray(int *array, int sz); | |
void mergeArrays(int arr1[], int arr2[], int n1, | |
int n2, int arr3[]); | |
int main() { | |
vector<int> a(SIZE); | |
int* leftArray = (int *)malloc((SIZE/2+1) * sizeof(int)); | |
int* rightArray = (int *)malloc((SIZE/2+1) * sizeof(int)); | |
for (int m = 0; m < SIZE; m++) { | |
a[m] = rand()%10; | |
} | |
for (int i = 0; i < SIZE/2; ++i) leftArray[i] = a[i]; | |
for (int i = 0, j = SIZE/2; i < SIZE/2; ++i, j++) { | |
rightArray[i] = a[j]; | |
} | |
thread t1 (CountingSort, leftArray); | |
thread t2 (CountingSort, rightArray); | |
t1.join(); | |
t2.join(); | |
int sortedArray[SIZE]; | |
mergeArrays(leftArray, rightArray, SIZE/2, SIZE/2, sortedArray); | |
// printArray(leftArray, SIZE/2); | |
// printArray(rightArray, SIZE/2); | |
printArray(a); | |
printArray(sortedArray, SIZE); | |
cout << endl; | |
return 0; | |
} | |
void printArray(vector<int>& array){ | |
for (int i = 0; i < SIZE; ++i) cout << array[i] << ' '; | |
cout << endl; | |
} | |
void printArray(int *array, int sz){ | |
for (int i = 0; i < sz; ++i) cout << array[i] << ' '; | |
cout << endl; | |
} | |
void mergeArrays(int arr1[], int arr2[], int n1, | |
int n2, int arr3[]) { | |
int i = 0, j = 0, k = 0; | |
while (i<n1 && j <n2) { | |
if (arr1[i] < arr2[j]) | |
arr3[k++] = arr1[i++]; | |
else | |
arr3[k++] = arr2[j++]; | |
} | |
while (i < n1) | |
arr3[k++] = arr1[i++]; | |
while (j < n2) | |
arr3[k++] = arr2[j++]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment