Advertisement
max-black

32

May 16th, 2025
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.26 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.concurrent.RecursiveAction;
  3. import java.util.concurrent.ForkJoinPool;
  4.  
  5. public class ParallelQuickSort extends RecursiveAction {
  6.     private final int[] array;
  7.     private final int low;
  8.     private final int high;
  9.     private static final int THRESHOLD = 1000;  // 阈值,决定何时顺序排序
  10.  
  11.     public ParallelQuickSort(int[] array, int low, int high) {
  12.         this.array = array;
  13.         this.low = low;
  14.         this.high = high;
  15.     }
  16.  
  17.     @Override
  18.     protected void compute() {
  19.         if (high - low < THRESHOLD) {
  20.             Arrays.sort(array, low, high + 1);  // 小任务直接排序
  21.         } else {
  22.             int pivotIndex = partition(array, low, high);  // 分区操作
  23.             ParallelQuickSort left = new ParallelQuickSort(array, low, pivotIndex - 1);
  24.             ParallelQuickSort right = new ParallelQuickSort(array, pivotIndex + 1, high);
  25.             invokeAll(left, right);  // 并行处理左右子任务
  26.         }
  27.     }
  28.  
  29.     // 分区函数(Hoare分区法)
  30.     private int partition(int[] array, int low, int high) {
  31.         int pivot = array[high];  // 选择最后一个元素为基准
  32.         int i = low - 1;
  33.         for (int j = low; j < high; j++) {
  34.             if (array[j] <= pivot) {
  35.                 i++;
  36.                 swap(array, i, j);
  37.             }
  38.         }
  39.         swap(array, i + 1, high);
  40.         return i + 1;
  41.     }
  42.  
  43.     private void swap(int[] array, int i, int j) {
  44.         int temp = array[i];
  45.         array[i] = array[j];
  46.         array[j] = temp;
  47.     }
  48.  
  49.     // 测试代码
  50.     public static void main(String[] args) {
  51.         int[] array = new int[100000];
  52.         // 初始化数组(示例)
  53.         Random random = new Random();
  54.         for (int i = 0; i < array.length; i++) {
  55.             array[i] = random.nextInt(1_000_000);
  56.         }
  57.         ForkJoinPool pool = new ForkJoinPool();
  58.         ParallelQuickSort task = new ParallelQuickSort(array, 0, array.length - 1);
  59.         pool.invoke(task);
  60.         // 验证排序结果
  61.         for (int i = 0; i < array.length - 1; i++) {
  62.             if (array[i] > array[i + 1]) {
  63.                 System.out.println("Error: Not sorted!");
  64.                 break;
  65.             }
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement