Advertisement
LikeRampage

C++ Multithreading code on Sort array CHATGPT

Apr 26th, 2024
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.97 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. void quicksort(std::vector<int>& arr, int left, int right) {
  7.     if (left >= right) {
  8.         return;
  9.     }
  10.    
  11.     int pivot = arr[(left + right) / 2];
  12.     int i = left;
  13.     int j = right;
  14.    
  15.     while (i <= j) {
  16.         while (arr[i] < pivot) {
  17.             i++;
  18.         }
  19.         while (arr[j] > pivot) {
  20.             j--;
  21.         }
  22.         if (i <= j) {
  23.             std::swap(arr[i], arr[j]);
  24.             i++;
  25.             j--;
  26.         }
  27.     }
  28.    
  29.     std::thread t1(quicksort, std::ref(arr), left, j);
  30.     std::thread t2(quicksort, std::ref(arr), i, right);
  31.    
  32.     t1.join();
  33.     t2.join();
  34. }
  35.  
  36. int main() {
  37.     std::vector<int> arr = {9, 3, 7, 1, 5, 8, 2, 6, 4};
  38.    
  39.     quicksort(arr, 0, arr.size() - 1);
  40.    
  41.     std::cout << "Sorted array: ";
  42.     for (int num : arr) {
  43.         std::cout << num << " ";
  44.     }
  45.     std::cout << std::endl;
  46.    
  47.     return 0;
  48. }
Tags: C++
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement