Nguythang

MergeSort

May 23rd, 2016
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | None | 0 0
  1. public class MergeSort {
  2.     public static void checkInput(int n) {
  3.         int[] array;
  4.  
  5.         Scanner scanner = new Scanner(System.in);
  6.         while (true) {
  7.             try {
  8.                 System.out.println("Enter the number of array: ");
  9.                 n = Integer.parseInt(scanner.nextLine());
  10.                 array = new int[n];
  11.                 if (n <= 0) {
  12.                     throw new Exception();
  13.                 }
  14.                 break;
  15.             } catch (Exception e) {
  16.                 System.out.println("Wrong input. Try again!");
  17.             }
  18.         }
  19.         sorting(array, n);
  20.     }
  21.  
  22.     public static void sorting(int[] array, int n) {
  23.         int i;
  24.         Random random = new Random();
  25.         array = new int[n];
  26.         System.out.println("Unsorted array: ");
  27.         for (i = 0; i < n; i++) {
  28.             array[i] = random.nextInt(n);
  29.         }
  30.         System.out.println(Arrays.toString(array));
  31.         System.out.println("Sorted array: ");
  32.         mergeSort(array, 0, n);
  33.         System.out.println(Arrays.toString(array));
  34.     }
  35.  
  36.     public static void mergeSort(int[] a, int low, int high)
  37.     {
  38.         int N = high - low;
  39.         if (N <= 1)
  40.             return;
  41.         int mid = low + N / 2;
  42.         // recursively sort
  43.         mergeSort(a, low, mid);
  44.  
  45.         mergeSort(a, mid, high);
  46.         // merge two sorted sub-arrays
  47.         int[] temp = new int[N];
  48.         int i = low, j = mid;
  49.         for (int k = 0; k < N; k++)
  50.         {
  51.             if (i == mid)
  52.                 temp[k] = a[j++];
  53.             else if (j == high)
  54.                 temp[k] = a[i++];
  55.             else if (a[j] < a[i])
  56.                 temp[k] = a[j++];
  57.             else
  58.                 temp[k] = a[i++];
  59.         }
  60.         for (int k = 0; k < N; k++)
  61.             a[low + k] = temp[k];
  62.     }
  63.  
  64.     public static void main(String[] args) {
  65.         int n = 0;
  66.         checkInput(n);
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment