-
Notifications
You must be signed in to change notification settings - Fork 0
/
912.Sort An Array.java
47 lines (41 loc) · 1.17 KB
/
912.Sort An Array.java
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
class Solution {
public int[] sortArray(int[] nums) {
int si=0;
int ei=nums.length-1;
mergeSort(nums,si,ei);
return nums;
}
private void mergeSort(int arr[],int si, int ei){
if(si>=ei){
return ;
}
int mid=si+(ei-si)/2;
mergeSort(arr,si,mid);
mergeSort(arr,mid+1,ei);
merge(arr,si,mid,ei);
}
private void merge(int[] nums, int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
for (int i = 0; i < n1; ++i)
leftArray[i] = nums[left + i];
for (int i = 0; i < n2; ++i)
rightArray[i] = nums[mid + 1 + i];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
nums[k++] = leftArray[i++];
} else {
nums[k++] = rightArray[j++];
}
}
while (i < n1) {
nums[k++] = leftArray[i++];
}
while (j < n2) {
nums[k++] = rightArray[j++];
}
}
}