Nguythang

Untitled

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