Repository navigation
Expand file tree
/
Copy pathMergeSort.java
More file actions
78 lines (69 loc) · 1.82 KB
/
Copy pathMergeSort.java
File metadata and controls
78 lines (69 loc) · 1.82 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
package com.interview.sort;
/**
* http://en.wikipedia.org/wiki/Merge_sort
* Test cases
* 1 element
* 2 element
* negative numbers
* already sorted
* reverse sorted
*/
public class MergeSort {
public void sort(int input[]){
sort(input, 0, input.length-1);
}
private void sort(int input[], int low, int high){
if(low >= high){
return;
}
int middle = (low + high)/2;
sort(input, low, middle);
sort(input, middle+1, high);
sortedMerge(input,low,high);
}
private void sortedMerge(int input[], int low, int high){
int middle = (low+high)/2;
int temp[] = new int[high-low+1];
int i = low;
int j = middle+1;
int r = 0;
while(i <= middle && j <= high){
if(input[i] <= input[j]){
temp[r++] = input[i++];
}else{
temp[r++] = input[j++];
}
}
while(i <= middle){
temp[r++] = input[i++];
}
while(j <= high){
temp[r++] = input[j++];
}
i = low;
for(int k=0; k < temp.length;){
input[i++] = temp[k++];
}
}
public void printArray(int input[]){
for(int i : input){
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String args[]){
int input1[] = {1};
int input2[] = {4,2};
int input3[] = {6,2,9};
int input4[] = {6,-1,10,4,11,14,19,12,18};
MergeSort ms = new MergeSort();
ms.sort(input1);
ms.sort(input2);
ms.sort(input3);
ms.sort(input4);
ms.printArray(input1);
ms.printArray(input2);
ms.printArray(input3);
ms.printArray(input4);
}
}