You are on page 1of 9

1

PARALLEL QUICK
SORT

Week14_Lecture40
Parallel Quicksort 2

 It uses the divide and conquer approach.


 This makes quicksort amenable to parallelization using task parallelism.
 It uses parallelization and some processes are solved concurrently.
How to perform a parallel quicksort 3

(Approach 1)

 Start a process to find pivot and partition the list into two, p < =p > p.
 At each step, start p processes proportional to n partitions.
 Each process finds the pivot element and divides the list based on the selected
pivot.
 Finally processes values are merged, and a sorted list is returned.
Pictorial
 This method is actually not optimized as the pivot has
been chosen poorly. representation
 The time complexity we get here is O(n²).

 So, this method is referred to as the naive approach


sometimes

But, we can optimize it

Instead of doubling the number of processes at each


step, this approach uses n number of processes
throughout the algorithm to find the pivot element and
rearrange the list. All these processes run concurrently at
each step sorting the lists.
5

IMPLEMENTATION
OF PARALLEL
QUICK SORT
USING OPENMP
Implementation [1/4] 6

void swap(int* a, int* b)


{
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int start, int end)
{
int pivot = arr[end];
int i = (start - 1);
Implementation [2/4] 7

for (int j = start; j <= end - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[end]);
return (i + 1);
}
Implementation [3/4] 8

void quicksort(int arr[], int start, int end)


{
int index;
if (start < end) {
index = partition(arr, start, end);
#pragma omp parallel sections
{
#pragma omp section
{
quicksort(arr, start, index - 1); }
Implementation [4/4] 9

#pragma omp section


{
quicksort(arr, index + 1, end);
}
}
}
}

You might also like