forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0912-sort-an-array.java
41 lines (39 loc) · 1.06 KB
/
0912-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
class Solution {
//Using Merge Sort
public int[] sortArray(int[] nums) {
mergeSort(nums, 0, nums.length-1);
return nums;
}
public void mergeSort(int []arr, int low, int high){
if(low >= high) return;
int mid = (low+high)/2;
mergeSort(arr, low, mid);
mergeSort(arr, mid+1, high);
merge(arr, low, high, mid);
}
public void merge(int []arr, int low, int high, int mid){
ArrayList<Integer> temp = new ArrayList<>();
int left = low;
int right = mid+1;
while(left <= mid && right <= high){
if(arr[left] <= arr[right]){
temp.add(arr[left]);
left++;
}else{
temp.add(arr[right]);
right++;
}
}
while(left <= mid){
temp.add(arr[left]);
left++;
}
while(right <= high){
temp.add(arr[right]);
right++;
}
for(int i=low; i<= high; i++){
arr[i] = temp.get(i-low);
}
}
}