Skip to content

Instantly share code, notes, and snippets.

@HassanElDesouky
Created February 27, 2021 01:21
Show Gist options
  • Save HassanElDesouky/1e0dac9418ab4695532bc91d246082e3 to your computer and use it in GitHub Desktop.
Save HassanElDesouky/1e0dac9418ab4695532bc91d246082e3 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#include <algorithm>
using namespace std;
using namespace std::chrono;
int SIZE = 10;
void indexSort(int arr[], int n) {
int index[n];
for (int i = 0; i < n; ++i) index[i] = i;
for(int i=0;i < n;i++) {
for(int j=i+1;j < n;j++) {
if(arr[index[i]] > arr[index[j]]) {
int temp = index[i];
index[i] = index[j];
index[j] = temp;
}
}
}
vector<int> v;
for (int i = 0; i < n; ++i) {
v.push_back(arr[index[i]]);
}
for (int i = 0; i < n; ++i) arr[i] = v[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 (indexSort, leftArray, SIZE/2);
thread t2 (indexSort, rightArray, SIZE/2);
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