#include #include #include #define NUM_THREADS 4 // Number of threads (should be even) #define ARRAY_SIZE 8 // Size of the array int array[ARRAY_SIZE]; pthread_barrier_t barrier; // Function to swap two array elements void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // Function executed by each thread void *sort(void *arg) { int thread_part = *(int*)arg; for (int phase = 0; phase < ARRAY_SIZE; phase++) { // Determine pairs for this phase int index = thread_part * 2 + (phase % 2); // Compare and swap if needed if (index < ARRAY_SIZE - 1 && array[index] > array[index + 1]) { swap(&array[index], &array[index + 1]); } // Wait for all threads to finish this phase pthread_barrier_wait(&barrier); } pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int thread_args[NUM_THREADS]; int status; // Initialize array with random values for (int i = 0; i < ARRAY_SIZE; i++) { array[i] = rand() % 100; // Random numbers between 0 and 99 } // Initialize barrier pthread_barrier_init(&barrier, NULL, NUM_THREADS); // Create threads for sorting for (int i = 0; i < NUM_THREADS; i++) { thread_args[i] = i; status = pthread_create(&threads[i], NULL, sort, (void *)&thread_args[i]); if (status != 0) { printf("ERROR; return code from pthread_create() is %d\n", status); exit(-1); } } // Wait for all threads to complete for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } // Print the sorted array printf("Sorted Array: "); for (int i = 0; i < ARRAY_SIZE; i++) { printf("%d ", array[i]); } printf("\n"); // Clean up and exit pthread_barrier_destroy(&barrier); return 0; }