forked from pratyushmp/code_opensource_2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergesort.java
More file actions
89 lines (78 loc) · 1.48 KB
/
Mergesort.java
File metadata and controls
89 lines (78 loc) · 1.48 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
package practice;
import java.util.Random;
import java.util.Scanner;
public class Mergesort {
public static void mergesort(int a[], int low, int high)
{
int mid;
if(high>low)
{
mid = (high+low)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
public static void merge(int a[], int low, int mid, int high)
{
int k = low,i=low,j=mid+1;
int c[] = new int[100];
while((i<=mid) && (j<=high))
{
if(a[i]<=a[j])
{
c[k] = a[i];
i+=1;
}
else
{
c[k] = a[j];
j+=1;
}
k+=1;
}
while(i<=mid)
{
c[k] = a[i];
k+=1;
i+=1;
}
while(j<=high)
{
c[k] = a[j];
k+=1;
j+=1;
}
for(i=low;i<=high;i++)
a[i] = c[i];
}
public static void main(String args[])
{
int i,n;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of elements");
n = in.nextInt();
Random rand = new Random();
int a[] = new int[100];
try
{
for(i=0;i<n;i++)
a[i] = rand.nextInt(50);
System.out.println("Random elements generated are:");
for(i=0;i<n;i++)
System.out.println(a[i]+" ");
long start_t = System.nanoTime();
mergesort(a,0,n-1);
long end_t = System.nanoTime();
long t = end_t-start_t;
System.out.println("Sorted elements are:");
for(i=0;i<n;i++)
System.out.println(a[i]+" ");
System.out.println("Time taken to sort:"+t);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array overload");
}
}
}