Skip to content

Commit 6fa2a66

Browse files
add 912
1 parent e11ca76 commit 6fa2a66

File tree

1 file changed

+50
-3
lines changed
  • src/main/java/com/fishercoder/solutions/firstthousand

1 file changed

+50
-3
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,59 @@
11
package com.fishercoder.solutions.firstthousand;
22

3-
import java.util.Arrays;
4-
53
public class _912 {
64
public static class Solution1 {
5+
/**
6+
* Implementation of MergeSort which is a stable sort, unlike QuickSort which isn't stable.
7+
*/
78
public int[] sortArray(int[] nums) {
8-
Arrays.sort(nums);
9+
//use a helder function to take in two additional parameters for the ease of recursion
10+
return sort(nums, 0, nums.length - 1);
11+
}
12+
13+
//this is the recursive function
14+
private int[] sort(int[] nums, int left, int right) {
15+
//this condition keeps dividing the array until nums becomes one individual item and then it goes back to the call stack
16+
if (left < right) {
17+
int mid = left + (right - left) / 2;
18+
sort(nums, left, mid);
19+
sort(nums, mid + 1, right);
20+
merge(nums, left, mid, right);
21+
}
922
return nums;
1023
}
24+
25+
private void merge(int[] nums, int left, int mid, int right) {
26+
int leftSize = mid - left + 1;
27+
int rightSize = right - mid;
28+
//use two temp array to copy the original values in the input before we overwrite them
29+
int[] leftHalf = new int[leftSize];
30+
int[] rightHalf = new int[rightSize];
31+
for (int i = 0; i < leftSize; i++) {
32+
//this index is key: it should be nums[left + i] as it should start from left instead of zero
33+
leftHalf[i] = nums[left + i];
34+
}
35+
for (int i = 0; i < rightSize; i++) {
36+
//similarly, this index is key as well: it should be nums[mid + i + 1] instead of starting from zero
37+
rightHalf[i] = nums[mid + i + 1];
38+
}
39+
int i = 0;
40+
int j = 0;
41+
//again, this index k = left is key, it should start from left instead of 0
42+
int k = left;
43+
while (i < leftSize && j < rightSize) {
44+
if (leftHalf[i] < rightHalf[j]) {
45+
nums[k++] = leftHalf[i++];
46+
} else {
47+
nums[k++] = rightHalf[j++];
48+
}
49+
}
50+
51+
while (i < leftSize) {
52+
nums[k++] = leftHalf[i++];
53+
}
54+
while (j < rightSize) {
55+
nums[k++] = rightHalf[j++];
56+
}
57+
}
1158
}
1259
}

0 commit comments

Comments
 (0)