Merge Sort java please include comments if possible and try

Merge Sort java, please include comments if possible and try to post a mostly orignal answer

Generate an array with 100 random integers between 0 and 1000 Print the original array to the screen Use your merge sort algorithm to sort the array from lowest to highest Print the sorted array to the screen

Solution

public class MergeSort {
   
    private int[] array;
    private int[] tempMergArr;
    private int length;

    public static void main(String a[]){
       
        int[] input;
   Random rand=Math.random();
   int i=0;
  
   while(i<100){
       input[i]=rand.nextInt(100); //generates random number below 100
       i++;
   }

   System.out.println(\"Before merge sort:\");
   ms.print(input);

        MergeSort ms = new MergeSort();
        ms.sort(input);

   System.out.println(\"After merge sort:\");
   ms.print(input);

        }
    }

    public void print(int arr[])
    {
   for(int i:arr){
            System.out.print(i);
            System.out.print(\" \");
    }
   
    public void sort(int input[]) {
        this.array = input;
        this.length = input.length;
        this.tempMergArr = new int[length];
        doMergeSort(0, length - 1);
    }

    private void doMergeSort(int lowerIndex, int higherIndex) {
       
        if (lowerIndex < higherIndex) {
            int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
            // Below step sorts the left side of the array
            doMergeSort(lowerIndex, middle);
            // Below step sorts the right side of the array
            doMergeSort(middle + 1, higherIndex);
            // Now merge both sides
            mergeParts(lowerIndex, middle, higherIndex);
        }
    }

    private void mergeParts(int lowerIndex, int middle, int higherIndex) {

        for (int i = lowerIndex; i <= higherIndex; i++) {
            tempMergArr[i] = array[i];
        }
        int i = lowerIndex;
        int j = middle + 1;
        int k = lowerIndex;
        while (i <= middle && j <= higherIndex) {
            if (tempMergArr[i] <= tempMergArr[j]) {
                array[k] = tempMergArr[i];
                i++;
            } else {
                array[k] = tempMergArr[j];
                j++;
            }
            k++;
        }
        while (i <= middle) {
            array[k] = tempMergArr[i];
            k++;
            i++;
        }

    }
}

Merge Sort java, please include comments if possible and try to post a mostly orignal answer Generate an array with 100 random integers between 0 and 1000 Print
Merge Sort java, please include comments if possible and try to post a mostly orignal answer Generate an array with 100 random integers between 0 and 1000 Print

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site