About
import java.util.Arrays;
public class test { private static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
private static void mergeArrays(int[] arr, int[][] subArrays) {
int k = 0;
for (int[] subArray : subArrays) {
System.arraycopy(subArray, 0, arr, k, subArray.length);
k += subArray.length;
}
}
public static void main(String[] args) throws InterruptedException {
int[] arr = new int[40000];
// Populate the array with random numbers or any other way
int n = 4; // Number of sub-arrays and threads
int[][] subArrays = new int[n][];
int chunkSize = arr.length / n;
// Create and start sorting threads
Thread[] sortThreads = new Thread[n];
for (int i = 0; i < n; i++) {
int startIndex = i * chunkSize;
int endIndex = (i == n - 1) ? arr.length : (i + 1) * chunkSize;
subArrays[i] = Arrays.copyOfRange(arr, startIndex, endIndex);
int[] subArray = subArrays[i];
sortThreads[i] = new Thread(() -> bubbleSort(subArray));
sortThreads[i].start();
}
// Wait for sorting threads to finish
for (Thread sortThread : sortThreads) {
sortThread.join();
}
// Create and start merging thread
Thread mergeThread = new Thread(() -> mergeArrays(arr, subArrays));
mergeThread.start();
// Wait for merging thread to finish
mergeThread.join();
// Display the sorted array
System.out.println(Arrays.toString(arr));
}
}