Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
2.7 kB
1
Indexable
Never
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;

class Thread_method{
    synchronized int[] refer(int[] arr, int start, int end) {
        System.out.println("Sorting from index "+start +" to " + end);
        Arrays.sort(arr, start, end);
        System.out.println("Sorting done from index "+start +" to " + end);
        return Arrays.copyOfRange(arr, start, end);
    }
}

class Thread_call implements Runnable{
    Thread thread;
    Thread_method goal;
    int first, last;
    int[] arr;
    int[] output;
    Thread_call(int[] arr, int i, int div, int X, Thread_method target){
        this.arr = arr;
        this.goal = target;
        this.first = i*div;
        this.last = (i+1)*div;
        if(i == X-1) this.last = arr.length;

        thread = new Thread(this);
        thread.start();
    }
    @Override
    public void run() {

        this.output = goal.refer(arr, first, last);
    }

}

class Main {
    public static int[] merge(int[] arr1, int[] arr2){
        int[] arr = new int[1000];
        int i = 0, j = 0, k=0;
        int n1 = arr1.length;
        int n2 = arr2.length;

        while (i < n1 && j < n2) {
            if (arr1[i] <= arr2[j]) {
                arr[k] = arr1[i];
                i++;
            }
            else {
                arr[k] = arr2[j];
                j++;
            }
            k++;
        }
        while (i < n1) {
            arr[k] = arr1[i];
            i++;
            k++;
        }
        while (j < n2) {
            arr[k] = arr2[j];
            j++;
            k++;
        }

        return Arrays.copyOfRange(arr, 0, k);
    }

    public static void main(String[] args) {
        int[] arr = {6,7,1,3,2,4,5,11};
        Thread_call[] tc = new Thread_call[100];
        Scanner sc=new Scanner(System.in);
        int X = sc.nextInt();
        int div = arr.length/X;

        Thread_method goal = new Thread_method();
        for(int i=0;i<X;i++)
        {
            tc[i] = new Thread_call(arr, i, div, X, goal);
        }

        while (true){
            boolean finish = true;
            for(int i=0;i<X;i++){
                if(tc[i].thread.isAlive()){
                    finish = false;
                }
            }
            if(finish) break;
        }

        int [] arr3 = tc[0].output;
        for(int i=1;i<X;i++)
        {
            arr3 = Main.merge(arr3, tc[i].output);
        }

        System.out.println();
        System.out.print("Final sorted array: ");
        for (int item: arr3) {
            System.out.print(item);
        }
    }

}