-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortTest.java
More file actions
56 lines (49 loc) · 1.12 KB
/
Copy pathMergeSortTest.java
File metadata and controls
56 lines (49 loc) · 1.12 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
package sortAlgorithm;
public class MergeSortTest {
public static void mergeSort(int[] array,int low,int high)
{
if(low < high)
{
int middle = (low + high)/2;
mergeSort(array, low, middle);
mergeSort(array, middle+1, high);
merge(array, low,middle, high);
}
}
static void merge(int[] array,int low,int middle,int high)
{
int[] helper = new int[array.length];
for(int i = low;i <= high;++i)
{
helper[i] = array[i];
}
int helperLeft = low;
int helperRight = middle + 1;
int current = low;
while(helperLeft <= middle && helperRight <= high)
{
if(helper[helperLeft] <= helper[helperRight])
{
array[current] = helper[helperLeft];
++helperLeft;
}
else {
array[current] = helper[helperRight];
++helperRight;
}
++current;
}
int reminder = middle - helperLeft;
for(int i = 0;i <= reminder;++i)
{
array[current+i] = helper[helperLeft+i];
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] test = {9,3,6,4,10,0,2,8,7,5,1};
mergeSort(test, 0, test.length-1);
for(int i:test)
System.out.print(i + " ");
}
}