forked from nitin-jaiman/JavaAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
96 lines (69 loc) · 1.69 KB
/
MergeSort.java
File metadata and controls
96 lines (69 loc) · 1.69 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 template, choose Tools | Templates
* and open the template in the editor.
*/
package com.nitin.jaiman;
/**
*
* @author nitin
*/
public class MergeSort {
public double generatearray(int n){
int tobesorted[]=new int[n];
for (int i = 0; i < n; i++) {
tobesorted[i] = (int) (Math.random() * 100);
}
for (int values : tobesorted) {
System.out.print(" [" + values + "] ");
}
System.out.println();
int size = tobesorted.length;
double start=System.currentTimeMillis();
divide(tobesorted);
double end=System.currentTimeMillis();
return end-start;
}
public void divide(int tobesorted[]){
int n=tobesorted.length;
if(n<2){
return;
}
int mid=n/2;
int left[]=new int[mid];
int right[]=new int[n-mid];
for(int i=0;i<=mid-1;i++){
left[i]=tobesorted[i];
}
System.arraycopy(tobesorted, mid, right, 0, n - mid);
divide(left);
divide(right);
sort(left,right,tobesorted);
}
public void sort(int left[],int right[],int tobesorted[]){
int leftsize=left.length;
int rightsize=right.length;
int totalsize=tobesorted.length;
int i = 0,j = 0,k=0;
while(i<leftsize&&j<rightsize){
if(left[i]<right[j]){
tobesorted[k]=left[i];
i++;
}
else if(left[i]>=right[j]){
tobesorted[k]=right[j];
j++;
}
k++;
}
while(i<leftsize){
tobesorted[k]=left[i];
i++;
k++;
}
while(j<rightsize){
tobesorted[k]=right[j];
j++;
k++;
}
}
}