Uh oh!
There was an error while loading. Please reload this page.
forked from TheAlgorithms/Java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
Latest commit
107 lines (100 loc) · 2.97 KB
/
Copy pathMergeSort.java
File metadata and controls
107 lines (100 loc) · 2.97 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
97
98
99
100
101
102
103
104
105
106
107
importjava.util.Scanner;
/**
* Merge Sort
*
*/
publicclassMergeSort {
privateint[] array;
privateint[] tempMergArr;
privateintlength;
/**
* Sorts {@code inputArr} with merge sort algorithm.
*
* @param inputArr
*/
publicfinalvoidsort(intinputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = newint[this.length];
this.mergeSort(0, this.length - 1);
}
/**
* Partitions Array into recursively smaller pieces.
*
* @param lowerIndex
* lower bound to include in the first partition
* @param higherIndex
* upper bound to include in the third partition
*/
privatevoidmergeSort(intlowerIndex, inthigherIndex) {
if (lowerIndex < higherIndex) {
intmiddle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
this.mergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
this.mergeSort(middle + 1, higherIndex);
// Now merge both sides
this.mergeParts(lowerIndex, middle, higherIndex);
}
}
/**
* Merges partitions.
*
* @param lowerIndex
* @param middle
* @param higherIndex
*/
privatevoidmergeParts(intlowerIndex, intmiddle, inthigherIndex) {
for (inti = lowerIndex; i <= higherIndex; i++) {
this.tempMergArr[i] = this.array[i];
}
inti = lowerIndex;
intj = middle + 1;
intk = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (this.tempMergArr[i] <= this.tempMergArr[j]) {
this.array[k] = this.tempMergArr[i];
i++;
} else {
this.array[k] = this.tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
this.array[k] = this.tempMergArr[i];
k++;
i++;
}
}
/**
* Gets input to sort.
*
* @return unsorted array of integers to sort
*/
publicstaticint[] getInput() {
finalintnumElements = 6;
int[] unsorted = newint[numElements];
Scannerinput = newScanner(System.in);
System.out.println("Enter any 6 Numbers for Unsorted Array : ");
for (inti = 0; i < numElements; i++) {
unsorted[i] = input.nextInt();
}
input.close();
returnunsorted;
}
/**
* Main Method.
*
* @param args
*/
publicstaticvoidmain(Stringargs[]) {
int[] inputArr = getInput();
MergeSortmergeSort = newMergeSort();
mergeSort.sort(inputArr);
for (inti : inputArr) {
System.out.print(i);
System.out.print(" ");
}
}
}