-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortDemo.java
More file actions
96 lines (95 loc) · 2.54 KB
/
MergeSortDemo.java
File metadata and controls
96 lines (95 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* 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 DAA;
/**
*
* @author dell
*/
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class MergeSortDemo {
static int size;
public static void main(String[]args)throws IOException
{
Scanner in=new Scanner(System.in);
System.out.println("enter the no.of elements to be started:(>5000):");
size=in.nextInt();
int inputArr[]=new int [size];
genRandomNumbers(inputArr);
long startTime=System.nanoTime();
mergesort(inputArr,0,size-1);
long estimatedTime=System.nanoTime()-startTime;
PrintWriter outA=new PrintWriter(new File("msort.txt"));
for(int i=0;i<inputArr.length;i++)
{
outA.println(inputArr[i]);
}
outA.close();
System.out.println("the time complexity for best,average and worst case is"+(estimatedTime/1000000.0)+"ms");
}
public static void genRandomNumbers(int inputArr[])throws IOException
{
int number,count=0;
Random rand=new Random();
PrintWriter out=new PrintWriter(new File("random.txt"));
while (count<size)
{
number=rand.nextInt(size)+1;
out.println(number);
out.print("");
inputArr[count]=number;
count++;
}
out.close();
System.out.println("the total number generated:"+count);
}
public static void merge(int a[],int low,int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
int c[]=new int[1000000];
while(i<=mid&&j<=high)
{
if(a[i]<a[j])
{
c[k]=a[i];
k=k+1;
i=i+1;
}
else
{
c[k]=a[j];
j=j+1;
k=k+1;
}
}
while(i<=mid)
{
c[k++]=a[i++];
}
while(j<=high)
{
c[k++]=a[j++];
}
for(i=low;i<=high;i++)
{
a[i]=c[i];
}
}
public static void mergesort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
}