Advertisement
chowdhury_riham

MergeSort

Jan 13th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5.  
  6. //Created by riham on 1/12/2018.
  7. public class megreSort {
  8.     public static void main (String [] args){
  9.         Scanner sc= new Scanner(System.in);
  10.         int j=0;
  11.         System.out.println("Please Enter the numbers and When finish Write DONE");
  12.         ArrayList<String> list = new ArrayList<String>();
  13.         list.add(sc.nextLine());
  14.         while (!list.get(j).equalsIgnoreCase("DONE")) {
  15.             list.add(sc.nextLine());
  16.             j++;
  17.         }
  18.         list.remove(j);
  19.         int[] arry =new int[j];
  20.         arry = stringTOint(list, j);
  21.         arry=MergeSort(arry);
  22.         printSort(arry);
  23.     }
  24.     public static int[] stringTOint(ArrayList<String> list, int i) {
  25.         int[] arr = new int[i];
  26.         for (int index = 0; index < i; index++) {
  27.             arr[index] = Integer.valueOf(list.get(index));
  28.         }
  29.         return arr;
  30.     }
  31.     public static int [] MergeSort(int[] arr){
  32.         if(arr.length>1) {
  33.             int mid = arr.length / 2;
  34.             int[] left = new int[mid];
  35.             int[] right = new int[arr.length - mid];
  36.             for (int i = 0; i < mid; i++) left[i] = arr[i];
  37.             for (int i = mid; i < arr.length; i++) right[i - mid] = arr[i];
  38.             MergeSort(left);
  39.             MergeSort(right);
  40.             Merge(left, right, arr);
  41.         }
  42.         return arr;
  43.     }
  44.     public static void Merge(int [] left, int [] right, int [] arr){
  45.         int nL=left.length;
  46.         int nR=right.length;
  47.         int iL=0,iR=0,iArr=0; //iL=index of left,iR=index of right,iArr=index of arr
  48.         while (iL<nL && iR<nR){
  49.             if (left[iL]<right[iR]) {
  50.                 arr[iArr] = left[iL];
  51.                 iL++;
  52.             }
  53.             else {
  54.                 arr[iArr] = right[iR];
  55.                 iR++;
  56.             }
  57.             iArr++;
  58.         }
  59.         while(iL<nL){
  60.             arr[iArr]= left[iL];
  61.             iArr++;
  62.             iL++;
  63.         }
  64.         while(iR<nR){
  65.             arr[iArr]= right[iR];
  66.             iArr++;
  67.             iR++;
  68.         }
  69.     }
  70.     public static void printSort(int[] arr) {
  71.         System.out.println("The sorted List");
  72.         for (int p = 0; p < arr.length; p++) {
  73.             System.out.print(arr[p] + "\t");
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement