Advertisement
STANAANDREY

Untitled

Aug 27th, 2023
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4.  
  5. #define NUM_THREADS 4 // Number of threads to use
  6. #define ARRAY_SIZE 1000000 // Size of the sorted array
  7.  
  8. // Shared data structure to hold thread arguments
  9. struct ThreadArgs {
  10. int* arr;
  11. int target;
  12. int start;
  13. int end;
  14. int result;
  15. };
  16.  
  17. // Function to perform binary search on a sorted array
  18. void* binarySearch(void* arg) {
  19. struct ThreadArgs* threadArgs = (struct ThreadArgs*)arg;
  20. int* arr = threadArgs->arr;
  21. int target = threadArgs->target;
  22. int start = threadArgs->start;
  23. int end = threadArgs->end;
  24.  
  25. while (start <= end) {
  26. int mid = start + (end - start) / 2;
  27.  
  28. if (arr[mid] == target) {
  29. threadArgs->result = mid;
  30. return NULL;
  31. } else if (arr[mid] < target) {
  32. start = mid + 1;
  33. } else {
  34. end = mid - 1;
  35. }
  36. }
  37.  
  38. // If the target is not found, set the result to -1
  39. threadArgs->result = -1;
  40. return NULL;
  41. }
  42.  
  43. int main() {
  44. static int arr[ARRAY_SIZE] = {};
  45. for (int i = 0; i < ARRAY_SIZE; i++) arr[i] = i * 2;
  46. int target = 233333;
  47.  
  48. // Initialize the threads and their arguments
  49. pthread_t threads[NUM_THREADS];
  50. struct ThreadArgs threadArgs[NUM_THREADS];
  51.  
  52. int step = ARRAY_SIZE / NUM_THREADS;
  53. int remaining = ARRAY_SIZE % NUM_THREADS;
  54. int start = 0;
  55.  
  56. // Create threads and assign the binary search tasks
  57. for (int i = 0; i < NUM_THREADS; i++) {
  58. int end = start + step - 1;
  59. if (i < remaining) {
  60. end++;
  61. }
  62.  
  63. threadArgs[i].arr = arr;
  64. threadArgs[i].target = target;
  65. threadArgs[i].start = start;
  66. threadArgs[i].end = end;
  67.  
  68. pthread_create(&threads[i], NULL, binarySearch, (void*)&threadArgs[i]);
  69.  
  70. start = end + 1;
  71. }
  72.  
  73. // Wait for all threads to finish
  74. for (int i = 0; i < NUM_THREADS; i++) {
  75. pthread_join(threads[i], NULL);
  76. }
  77.  
  78. // Find the first thread that has found the target
  79. int result = -1;
  80. for (int i = 0; i < NUM_THREADS; i++) {
  81. if (threadArgs[i].result != -1) {
  82. result = threadArgs[i].result;
  83. break;
  84. }
  85. }
  86.  
  87. if (result != -1) {
  88. printf("Target %d found at index %d.\n", target, result);
  89. } else {
  90. printf("Target %d not found in the array.\n", target);
  91. }
  92.  
  93. return 0;
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement