1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
void merge2(int *a, int f1, int l1, int f2, int l2)
{
int smallest;
int first = f1;
int size = l2-f1 + 1;
int *temp = new int[size];
int i = 0;
while(l1-f1 >= 0 || l2-f2 >=0)
{
if(l1-f1 < 0)smallest = a[f2++];//first is empty
else if(l2-f2 < 0)smallest = a[f1++];//second is empty
else{ //both non empty
if(a[f1] < a[f2]) smallest = a[f1++];
else smallest = a[f2++];
}
temp[i++] = smallest;
}
//transfer
for(int j = 0; j<size; j++){
a[first+j] = temp[j];
}
delete [] temp;
}
void *mergeSort4(void *args)
{
struct merge_args *mergeargs = (struct merge_args*)args;
//Divide
if(mergeargs->last - mergeargs->first > 1)
{
int midpoint = (mergeargs->first + mergeargs->last)/2;
//Split into two new threads
pthread_t t1, t2;
struct merge_args mergeargs1, mergeargs2;
mergeargs1.a = mergeargs->a;
mergeargs1.first = mergeargs->first;
mergeargs1.last = midpoint;
mergeargs2.a = mergeargs->a;
mergeargs2.first = midpoint+1;
mergeargs2.last = mergeargs->last;
//CREATE THREADS
pthread_create(&t1, NULL, mergeSort4, (void*)&mergeargs1);
pthread_create(&t2, NULL, mergeSort4, (void*)&mergeargs2);
//Wait for threads to terminate?
pthread_join(t1, NULL);
pthread_join(t2, NULL);
//Merge
merge2(mergeargs->a, mergeargs->first, midpoint, midpoint+1, mergeargs->last);
}
else if(mergeargs->last - mergeargs->first == 1)
{
if(mergeargs->a[mergeargs->first] > mergeargs->a[mergeargs->last])
std::swap(mergeargs->a[mergeargs->first], mergeargs->a[mergeargs->last]);
}
}
|