-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge Sort
108 lines (97 loc) · 2.4 KB
/
Merge Sort
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
97
98
99
100
101
102
103
104
import java.util.Scanner;
import java.util.Random;
public class MergeSort {
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner scan=new Scanner(System.in);
Random ran=new Random();
long start,stop;
System.out.println("Enter no of elements");
int n=scan.nextInt();
int[] a=new int[n];
System.out.println(" Enter the choice 1: Best Case 2: Average Case 3: Worst Case");
int ch=scan.nextInt();
switch(ch)
{
case 1: System.out.println(" Best Case");
for(int i=0;i<n;i++)
a[i]=i;
break;
case 2: System.out.println(" Average Case");
for(int i=0;i<n;i++)
a[i]=ran.nextInt(n);
break;
case 3: System.out.println(" Worst Case");
for(int i=0;i<n;i++)
a[i]=n-i;
break;
}// end switch
//recording the start time
start=System.nanoTime();
//function call
Mergesort(a,0,n-1);
// recording the end time
stop=System.nanoTime();
display(a);
System.out.println("\nTime taken to sort " +a.length+ " elements =" +(stop-start));
}// end main
private static void display(int[] a)
{
// TODO Auto-generated method stub
System.out.println("the sorted array is");
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}//end display
//function o divide the array
public static void Mergesort(int[] a, int low, int high)
{
int mid;
if(low<high)// array contains more than one element
{
mid=(low+high)/2;// dividing the array in to two sub arrays
Mergesort(a, low, mid);// sorting sub arrays
Mergesort(a, mid+1, high);
Merge(a,low,mid,high);// combining or merging the sorted arrays
}
}// end Mergesort
//function to merge two sorted arrays
public static void Merge(int[] arr,int low,int mid,int high)
{
int k,h=low,i=low,j=mid+1;
int[] b=new int[arr.length];
while(h<=mid && j<=high)
{
if(arr[h]<=arr[j])
{
b[i]=arr[h];
h++;
}
else
{
b[i]=arr[j];
j++;
}
i++;
}// end while
if(h>mid) // for remaining elements in upper half
{
for(k=j;k<=high;k++)
{
b[i]=arr[k];
i++;
}
}
else // for remaining elements in lower half
{
for(k=h;k<=mid;k++)
{
b[i]=arr[k];
i++;
}
}
//copy the contents from auxiliary array i.e. from b to arr
for(k=low;k<=high;k++)
arr[k]=b[k];
}// end merge
}// end MergeSort class