Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.util.ArrayList;
- import java.util.Scanner;
- //Created by riham on 1/12/2018.
- public class megreSort {
- public static void main (String [] args){
- Scanner sc= new Scanner(System.in);
- int j=0;
- System.out.println("Please Enter the numbers and When finish Write DONE");
- ArrayList<String> list = new ArrayList<String>();
- list.add(sc.nextLine());
- while (!list.get(j).equalsIgnoreCase("DONE")) {
- list.add(sc.nextLine());
- j++;
- }
- list.remove(j);
- int[] arry =new int[j];
- arry = stringTOint(list, j);
- arry=MergeSort(arry);
- printSort(arry);
- }
- public static int[] stringTOint(ArrayList<String> list, int i) {
- int[] arr = new int[i];
- for (int index = 0; index < i; index++) {
- arr[index] = Integer.valueOf(list.get(index));
- }
- return arr;
- }
- public static int [] MergeSort(int[] arr){
- if(arr.length>1) {
- int mid = arr.length / 2;
- int[] left = new int[mid];
- int[] right = new int[arr.length - mid];
- for (int i = 0; i < mid; i++) left[i] = arr[i];
- for (int i = mid; i < arr.length; i++) right[i - mid] = arr[i];
- MergeSort(left);
- MergeSort(right);
- Merge(left, right, arr);
- }
- return arr;
- }
- public static void Merge(int [] left, int [] right, int [] arr){
- int nL=left.length;
- int nR=right.length;
- int iL=0,iR=0,iArr=0; //iL=index of left,iR=index of right,iArr=index of arr
- while (iL<nL && iR<nR){
- if (left[iL]<right[iR]) {
- arr[iArr] = left[iL];
- iL++;
- }
- else {
- arr[iArr] = right[iR];
- iR++;
- }
- iArr++;
- }
- while(iL<nL){
- arr[iArr]= left[iL];
- iArr++;
- iL++;
- }
- while(iR<nR){
- arr[iArr]= right[iR];
- iArr++;
- iR++;
- }
- }
- public static void printSort(int[] arr) {
- System.out.println("The sorted List");
- for (int p = 0; p < arr.length; p++) {
- System.out.print(arr[p] + "\t");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement