-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeSort.java
More file actions
60 lines (47 loc) · 1.4 KB
/
Copy pathMergeSort.java
File metadata and controls
60 lines (47 loc) · 1.4 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
package Sort;
import java.util.Arrays;
public class MergeSort {
public static void mergeSort(int[] nums, int low, int high){
int mid = low +(high -low)/2;
if(low < high){
mergeSort(nums, low, mid);
mergeSort(nums, mid+1, high);
merge(nums, low, mid, high);
// System.out.println(Arrays.toString(nums));
}
}
public static void merge(int[] nums, int low, int mid, int high){
int[] temp = new int[high-low+1];
int leftIndex = low;
int rightIndex = mid +1;
int k = 0;
while(leftIndex <= mid && rightIndex <= high){
if(nums[leftIndex] <= nums[rightIndex]){
temp[k] = nums[leftIndex];
leftIndex++;
}else{
temp[k] = nums[rightIndex];
rightIndex++;
}
k++;
}
while(leftIndex <= mid){
temp[k] = nums[leftIndex];
leftIndex++;
k++;
}
while(rightIndex <= high){
temp[k] = nums[rightIndex];
rightIndex++;
k++;
}
for(int i=0; i<temp.length; i++){
nums[low+i] = temp[i];
}
}
public static void main(String[] args){
int[] nums = {4,3,2,6,5,7,9,8};
mergeSort(nums,0,nums.length-1);
System.out.println(Arrays.toString(nums));
}
}