Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- class Demontration {
- public static void main(String[] args) throws Exception {
- MultiThreadedMergeSort.runTest();
- }
- }
- class MultiThreadedMergeSort {
- private final int[] duplicate;
- public MultiThreadedMergeSort(int size) {
- duplicate = new int[size];
- }
- public void sort(int left, int right, int[] array) throws InterruptedException {
- if (left >= right) {
- return;
- }
- int mid = (left + right) >> 1;
- Thread sortLeft =
- new Thread(
- () -> {
- try {
- sort(left, mid, array);
- } catch (InterruptedException e) {
- }
- });
- Thread sortRight =
- new Thread(
- new Runnable() {
- @Override
- public void run() {
- try {
- sort(mid + 1, right, array);
- } catch (InterruptedException e) {
- }
- }
- });
- sortLeft.start();
- sortRight.start();
- sortLeft.join();
- sortRight.join();
- for (int k = left; k <= right; k++) {
- duplicate[k] = array[k];
- }
- int i = left;
- int j = mid + 1;
- int index = left;
- while (i <= mid && j <= right) {
- if (duplicate[i] < duplicate[j]) {
- array[index++] = duplicate[i++];
- } else {
- array[index++] = duplicate[j++];
- }
- }
- while (i <= mid) {
- array[index++] = duplicate[i++];
- }
- while (j <= right) {
- array[index++] = duplicate[j++];
- }
- }
- public static void runTest() throws InterruptedException {
- Random random = new Random(System.currentTimeMillis());
- int size = 10;
- MultiThreadedMergeSort multiThreadedMergeSort = new MultiThreadedMergeSort(size);
- int[] array = new int[size];
- for (int i = 0; i < size; i++) {
- array[i] = random.nextInt(100);
- }
- System.out.println("Before sorting");
- printArray(array);
- multiThreadedMergeSort.sort(0, size - 1, array);
- System.out.println("After sorting");
- printArray(array);
- }
- private static void printArray(int[] array) {
- for (int i = 0; i < array.length; i++) {
- System.out.print(array[i] + " ");
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement