Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mpi.MPI;
- import java.util.concurrent.ThreadLocalRandom;
- public class HelloWorld {
- public static void main(String[] args) throws Exception{
- MPI.Init(args);
- double starttime, endtime;
- int rank = MPI.COMM_WORLD.Rank();
- int numranks = MPI.COMM_WORLD.Size();
- final int N = 10;
- int[] randomNumbers = new int[N];
- if(rank == 0){
- randomNumbers = generateRandomUnsortedIntArray(N, 9);
- System.out.println("unsorted array on rank 0 before bcast..");
- for (int i = 0; i <= N-1; i++) {
- System.out.print(randomNumbers[i] + " ");
- }
- System.out.println("");
- }
- MPI.COMM_WORLD.Bcast(randomNumbers, 0, N, MPI.INT, 0);
- //if (rank != 0) {
- // System.out.println("Broadcast complete on rank " + rank);
- //}
- MPI.COMM_WORLD.Barrier();
- if (rank == 0) {
- System.out.println("Rank 0 Sorted array:");
- starttime = System.nanoTime();
- insertionSort(randomNumbers);
- for (int i = 0; i <= N-1; i++) {
- System.out.print(randomNumbers[i] + " ");
- }
- endtime = System.nanoTime();
- System.out.println("");
- System.out.println("Execution time (rank 0):" + (endtime - starttime));
- }
- MPI.COMM_WORLD.Barrier();
- if(rank != 0){
- starttime = System.nanoTime();
- insertionSort(randomNumbers);
- //for (int i = 0; i <= N-1; i++) {
- // System.out.print(randomNumbers[i] + " ");
- //}
- endtime = System.nanoTime();
- System.out.println("");
- System.out.println("Execution time (rank "+ rank + "):" + (endtime - starttime));
- }
- if (rank == (numranks-1)) {
- for (int i = 0; i <= N-1; i++) {
- System.out.print(randomNumbers[i] + " ");
- }
- }
- MPI.Finalize();
- }
- private static int[] generateRandomUnsortedIntArray(int length, int maxInt){
- /*
- Generates an array of length length and fills it with random
- integers with a max value of maxInt then returns the array
- */
- // Create array variable
- int[] randArray = new int[length];
- // Iterate over 0..length
- for(int i = 0; i < length; i++){
- // Get next random number, then store it in array at current iteration point
- randArray[i] = ThreadLocalRandom.current().nextInt(maxInt);
- }
- // Return array
- return randArray;
- }
- public static void insertionSort(int[] array) {
- int N = array.length;
- for (int i = 1; i < N; i++) {
- int temp = array[i];
- int j = i-1;
- while (j >= 0 && array[j] > temp) {
- array[j+1] = array[j];
- j = j - 1;
- }
- array[j+1] = temp;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement