Merge Sort



Program In Java To Sort The Given Array Using Merge Sort Algorithm.

The Following Program Reads The Elements Of An Array From User And Then It Sorts The Array In Ascending Order Using Merge Sort Algorithm And Displays The Sorted Array

import java.io.*;
class MergeSort {
    void divide(int[] a, int low, int high) {
        if (low < high) {
            int mid = (low + high) / 2;
            divide(a, low, mid);
            divide(a, mid + 1, high);
            mSort(a, low, mid, high);
        }
    }
    void mSort(int[] a, int low, int mid, int high) {
        int[] b = new int[a.length];
        int i, j, k, l, h;
        for (i = low, j = mid + 1, k = low; i <= mid && j <= high; k++) {
            if (a[i] < a[j]) b[k] = a[i++];
            else b[k] = a[j++];
        }
        for (; i <= mid; i++, k++) b[k] = a[i];
        for (; j <= high; j++, k++) b[k] = a[j];
        for (i = low; i <= high; i++) a[i] = b[i];
    }
    public static void main(String[] arg) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Total Number Of Elements In An Array::");
        int t = Integer.parseInt(br.readLine());
        int[] arr = new int[t];
        for (int i = 0; i < t; i++) {
            System.out.print("\nEnter Element::");
            int e = Integer.parseInt(br.readLine());
            arr[i] = e;
        }
        //int []arr={5,4,15,16,17,3,2,1};
        MergeSort m = new MergeSort();
        m.divide(arr, 0, arr.length - 1);
        System.out.println("\n\nAfter Sorting Array Is::");
        for (int i = 0; i < arr.length; i++) System.out.println(arr[i]);
    }
}

OUTPUT:


Enter Total Number Of Elements In An Array::8

Enter Element::5

Enter Element::4

Enter Element::15

Enter Element::16

Enter Element::17

Enter Element::3

Enter Element::2

Enter Element::1
After Sorting Array Is::
1
2
3
4
5
15
16
17

Previous Post Next Post