0% found this document useful (0 votes)
5 views2 pages

Multithreaded Quick Sort in C

The document contains a C program that implements a multithreaded quicksort algorithm. It uses pthreads to sort an array of integers input by the user, dividing the sorting task into separate threads for each partition. The program prompts the user for the number of elements and the elements themselves, then outputs the sorted array.

Uploaded by

245122733014
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Multithreaded Quick Sort in C

The document contains a C program that implements a multithreaded quicksort algorithm. It uses pthreads to sort an array of integers input by the user, dividing the sorting task into separate threads for each partition. The program prompts the user for the number of elements and the elements themselves, then outputs the sorted array.

Uploaded by

245122733014
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h>
#include <stdlib.h>
#include <pthread.h>

#define MAX 100000

int arr[MAX];
int n;

typedef struct {
int low;
int high;
} ThreadData;

int partition(int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

int temp = arr[i + 1];


arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1;
}

void* quick_sort(void* arg) {


ThreadData* data = (ThreadData*)arg;
int low = data->low;
int high = data->high;

if (low < high) {


int pi = partition(low, high);

ThreadData left_data = {low, pi - 1};


ThreadData right_data = {pi + 1, high};

pthread_t left_thread, right_thread;

pthread_create(&left_thread, NULL, quick_sort, &left_data);


pthread_create(&right_thread, NULL, quick_sort, &right_data);

pthread_join(left_thread, NULL);
pthread_join(right_thread, NULL);
}

return NULL;
}

int main() {
printf("Enter number of elements: ");
scanf("%d", &n);

printf("Enter the elements:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

ThreadData data = {0, n - 1};


pthread_t main_thread;

pthread_create(&main_thread, NULL, quick_sort, &data);


pthread_join(main_thread, NULL);

printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

You might also like