Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9214117
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T01:54:17+00:00 2026-06-18T01:54:17+00:00

I am working on a homework problem where I have to create a Multithreaded

  • 0

I am working on a homework problem where I have to create a Multithreaded version of Merge Sort. I was able to implement it, but I am not able to stop the creation of threads. I looked into using an ExecutorService to limit the creation of threads but I cannot figure out how to implement it within my current code.

Here is my current Multithreaded Merge Sort. We are required to implement a specific strategy pattern so that is where my sort() method comes from.

@Override
public int[] sort(int[] list) {
    int array_size = list.length;
    list = msort(list, 0, array_size-1);
    return list;
}

int[] msort(int numbers[], int left, int right) {
    final int mid;
    final int leftRef = left;
    final int rightRef = right;
    final int array[] = numbers;
    if (left<right) {
        mid = (right + left) / 2;
        //new thread
        Runnable r1 = new Runnable(){
            public void run(){
                msort(array, leftRef, mid);     
            }
        };
        Thread t1 = new Thread(r1);
        t1.start();

        //new thread
        Runnable r2 = new Runnable(){
            public void run(){
                msort(array, mid+1, rightRef);
            }
        };
        Thread t2 = new Thread(r2);
        t2.start();
        //join threads back together
        try {
            t1.join();
            t2.join();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        merge(numbers, leftRef, mid, mid+1, rightRef);
    }
    return numbers;
}

void merge(int numbers[], int startA, int endA, int startB, int endB) {
    int finalStart = startA;
    int finalEnd = endB;
    int indexC = 0;
    int[] listC = new int[numbers.length];

    while(startA <= endA && startB <= endB){
        if(numbers[startA] < numbers[startB]){
            listC[indexC] = numbers[startA];
            startA = startA+1;
        }
        else{
            listC[indexC] = numbers[startB];
            startB = startB +1;
        }
        indexC++;
    }

    if(startA <= endA){
        for(int i = startA; i < endA; i++){
            listC[indexC]= numbers[i];
            indexC++;
        }
    }

    indexC = 0;
    for(int i = finalStart; i <= finalEnd; i++){
        numbers[i]=listC[indexC];
        indexC++;
    }
}

Any pointers would be gratefully received.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T01:54:19+00:00Added an answer on June 18, 2026 at 1:54 am

    Following @mcdowella’s comment, I also think that the fork/join framework is your best bet if you want to limit the number of threads that run in parallel.

    I know that this won’t give you any help on your homework, because you are probably not allowed to use the fork/join framework in Java7. However it is about to learn something, isn’t it?;)

    As I commented, I think your merge method is wrong. I can’t pinpoint the failure, but I have rewritten it. I strongly suggest you to write a testcase with all the edge cases that can happen during that merge method and if you verified it works, plant it back to your multithreaded code.

    @lbalazscs also gave you the hint that the fork/join sort is mentioned in the javadocs, however I had nothing else to do- so I will show you the solution if you’d implemented it with Java7.

    public class MultithreadedMergeSort extends RecursiveAction {
    
      private final int[] array;
      private final int begin;
      private final int end;
    
      public MultithreadedMergeSort(int[] array, int begin, int end) {
        this.array = array;
        this.begin = begin;
        this.end = end;
      }
    
      @Override
      protected void compute() {
        if (end - begin < 2) {
          // swap if we only have two elements
          if (array[begin] > array[end]) {
            int tmp = array[end];
            array[end] = array[begin];
            array[begin] = tmp;
          }
        } else {
          // overflow safe method to calculate the mid
          int mid = (begin + end) >>> 1;
          // invoke recursive sorting action
          invokeAll(new MultithreadedMergeSort(array, begin, mid),
              new MultithreadedMergeSort(array, mid + 1, end));
          // merge both sides
          merge(array, begin, mid, end);
        }
      }
    
      void merge(int[] numbers, int startA, int startB, int endB) {
        int[] toReturn = new int[endB - startA + 1];
        int i = 0, k = startA, j = startB + 1;
        while (i < toReturn.length) {
          if (numbers[k] < numbers[j]) {
            toReturn[i] = numbers[k];
            k++;
          } else {
            toReturn[i] = numbers[j];
            j++;
          }
          i++;
          // if we hit the limit of an array, copy the rest
          if (j > endB) {
            System.arraycopy(numbers, k, toReturn, i, startB - k + 1);
            break;
          }
          if (k > startB) {
            System.arraycopy(numbers, j, toReturn, i, endB - j + 1);
            break;
          }
        }
        System.arraycopy(toReturn, 0, numbers, startA, toReturn.length);
      }
    
      public static void main(String[] args) {
        int[] toSort = { 55, 1, 12, 2, 25, 55, 56, 77 };
        ForkJoinPool pool = new ForkJoinPool();
        pool.invoke(new MultithreadedMergeSort(toSort, 0, toSort.length - 1));
        System.out.println(Arrays.toString(toSort));
    
      }
    

    Note that the construction of your threadpool limits the number of active parallel threads to the number of cores of your processor.

    ForkJoinPool pool = new ForkJoinPool();
    

    According to it’s javadoc:

    Creates a ForkJoinPool with parallelism equal to
    java.lang.Runtime.availableProcessors, using the default thread
    factory, no UncaughtExceptionHandler, and non-async LIFO processing
    mode.

    Also notice how my merge method differs from yours, because I think that is your main problem. At least your sorting works if I replace your merge method with mine.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a homework problem here I've been working on; here is the description:
I am working on some homework here, but I have completely run out of
I am working on a homework problem, I'm close but need some help with
I have a problem with my homework assignment and I do not know where
I am working on my homework, but I am not sure how to calculate
I'm working on homework and I'm close but I am having an issue. I
I'm working on a homework project that requires me to create an object from
This is homework...I'm not asking for answers, I just have a bug I'm not
Good day, Stack Overflow. I have a homework assignment that I'm working on this
I'm working on a problem which we have to use semaphores to solve. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.