-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortAlgorithm.java
More file actions
53 lines (36 loc) · 1.3 KB
/
MergeSortAlgorithm.java
File metadata and controls
53 lines (36 loc) · 1.3 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
package com.java.cci.practice;
public class MergeSortAlgorithm {
public static void main (String[] args) {
int [] array = {43,12,4,89,78,100};
int[] auxArray = new int[array.length];
sort(array, auxArray, 0, array.length -1);
printArray(array);
}
private static void sort(int[] array, int[] auxArray, int low, int hi) {
if(hi <= low) return;
int mid = low + (hi-low)/2;
sort(array,auxArray,low, mid);
sort(array,auxArray,mid+1, hi);
mergeArray(array, auxArray,low,mid, hi);
}
public static void printArray(int [] input) {
System.out.print("[ ");
for (int i = 0; i < input.length; i++) {
System.out.print(" ");
System.out.print(input[i]);
if (i != input.length -1)
System.out.print(" ,");
}
System.out.print(" ]");
}
private static int mergeArray(int[] array, int[] auxArray, int low, int mid, int hi) {
int count = 0;
int i=low;
int j=mid+1;
int k=0;
// while loop is missing
if(low < mid) auxArray[k++] = array[i++];
else if(low> mid) auxArray[k++] = array[j++];
return count;
}
}