0

我正在尝试创建合并排序的多线程版本,并且为此使用执行器(如果有其他更好的方法,请告诉我)。我希望两个线程同时运行。我是 Executors 的新手,即使在看过一些教程后也很难编写代码。当然,除执行器之外的任何并行化方法都是最受欢迎的。

public static void ASC(int[] input_array, int left, int right, int[] temp_array) // Sorts in ascending order
{
    if(left < right)
    {
        int middle = ( left + right )>>>1 ; // Same as (left + right)/2, but avoids overflow for large left and right and is probably faster

    // I want to run these 2 codes in 2 threads simultaneously
        ASC(input_array, left, middle, temp_array);
        ASC(input_array, middle+1, right, temp_array);

    // And I want the execution to stop here until the threads are finished
    // I know invokeAll() will do the job but I cant seem to code it properly
    // Pls tell me how to do it properly along with what classes to import as Im new to Executors.
    // Any other method of parallelizing is most welcomed

    // The part below is the Merge Procedure
        int j = middle + 1;
        int temp_indx = left;
        int left2 = left;
        while((left <= middle) && (j <= right))
        {
            if (input_array[left] < input_array[j])
            {
                temp_array[temp_indx] = input_array[left];
                left = left + 1;
            }
            else
            {
                temp_array[temp_indx] = input_array[j];
                j = j + 1;
            }
            temp_indx = temp_indx + 1;
        }
        while(left <= middle)
        {
            temp_array[temp_indx] = input_array[left];
            left = left + 1;
            temp_indx = temp_indx + 1;
        }
        while(j <= right)
        {
            temp_array[temp_indx] = input_array[j];
            j = j + 1;
            temp_indx = temp_indx + 1;
        }
        while(right >= left2)
        {
            input_array[right] = temp_array[right];
            right = right - 1;
        }
    }
}
4

0 回答 0