-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge.java
More file actions
89 lines (66 loc) · 1.93 KB
/
Merge.java
File metadata and controls
89 lines (66 loc) · 1.93 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
/*
April 20, 2017
This program will implement the merge-sort algorithm
*/
public class Merge {
private int[] array;
private int[] tempMergArr; //temp
private int length;
public static void main(String a[])
{
int[] Arr = {22,23,24,6,7,13,55,14,65,70};
Merge m = new Merge();
m.sort(Arr);
for(int i:Arr)
{
System.out.print(i);
System.out.print(" ");
}
}
public void sort(int Arr[])
{
this.array = Arr;
this.length = Arr.length;
this.tempMergArr = new int[length];
MergeSort(0, length - 1); //assigns lowest val and highest val
}
/////////////////////////////////////////////////////////////////////////////////////////
public void MergeSort(int low, int high)
{ //locates mid point
if (low < high)
{
int middle = low + (high - low) / 2;
MergeSort(low, middle);
MergeSort(middle + 1, high);
merge(low, middle, high);
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public void merge(int low, int middle, int high) //merge
{
for (int i = low; i <= high; i++)
{
tempMergArr[i] = array[i];
}
int i = low;
int j = middle + 1;
int l = low;
while (i <= middle && j <= high)
{
if (tempMergArr[i] <= tempMergArr[j])
{
array[l] = tempMergArr[i];
i++;
} else {
array[l] = tempMergArr[j];
j++;
}
l++;
}
while (i <= middle) {
array[l] = tempMergArr[i];
l++;
i++;
}
}
}