Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package mergesort;
- import java.util.Scanner;
- /**
- *
- * @author manth
- */
- public class MergeSort {
- /**
- * @param args the command line arguments
- */
- static int n;
- static double input[];
- static String ALGO="MergeSort";
- public static void main(String[] args) {
- //input();
- randinput();
- System.out.println(" INPUT IS ");
- display(input);
- long startTime = System.currentTimeMillis();
- mergesort(input,0,input.length-1);
- Long endTime=System.currentTimeMillis();
- System.out.println("\n\ntime elapsed in sorting is "+ (endTime-startTime)+" Milliseconds \n\n");
- System.out.println("OUTPUT OF SORTED NUMBERS IS ");
- System.out.println("Numbers are sorted by "+ ALGO);
- display(input);
- }
- public static void display(double [] input)
- {
- for(int i=0;i<input.length;i++)
- {
- System.out.println(input[i]+" ");
- }
- }
- public static void randinput()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" BUBBLE SORT \n ENTER TOTAL NUMBERS TO SORT");
- try{
- n=Integer.parseInt(sc.nextLine());
- }catch(Exception e)
- {
- System.out.println(" Please Enter a valid integer "+e);
- }
- input=new double[n];
- for(int i=0;i<n;i++)
- {
- input[i]=Math.random()*1000;
- }
- }
- public static void input()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" \n ENTER TOTAL NUMBERS TO SORT");
- try{
- n=Integer.parseInt(sc.nextLine());
- }catch(Exception e)
- {
- System.out.println(" Please Enter a valid integer "+e);
- }
- input=new double[n];
- for(int i=0;i<n;i++)
- {
- input[i]=sc.nextInt();
- }
- System.out.println(" INPUT RECORDED ");
- System.out.println(" Numbers are getting sorted by algorithm: "+ ALGO);
- }
- ////////////////////////////////////////////////////////////////////////
- public static void mergesort(double input[],int low, int high)
- {
- int mid;
- if(low<high)
- {
- mid=(low+high)/2;
- mergesort(input,low,mid);
- mergesort(input,mid+1,high);
- merge(input,low,mid,mid+1,high);
- }
- }
- public static void merge(double input[],int l1,int u1,int l2,int u2)
- {
- double temp[]=new double[u2-l1+1];
- int n=0;
- int i=l1;
- int j=l2;
- while(i<=u1&&j<=u2)
- {
- temp[n++]=input[i]<input[j]?input[i++]:input[j++];
- }
- while(i<=u1)
- temp[n++]=input[i++];
- while(j<=u2)
- temp[n++]=input[j++];
- n=0;
- for(int k=l1;k<=u2;k++)
- input[k]=temp[n++];
- }
- /////////////////////////////////////////////////////////////////////
- }
Advertisement
Add Comment
Please, Sign In to add comment