-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeSort.java
58 lines (51 loc) · 1.15 KB
/
MergeSort.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
48
49
50
51
52
53
54
55
56
57
58
package sort;
public class MergeSort {
public static void main(String args[]){
int[] nums = {3,2,4,5,8,1,1,2};
int[] temp = new int[nums.length];
int low = 0;
int high = nums.length -1;
mergesort(nums,temp,low,high);
System.out.println("Merge Sort");
for(int i=0; i<=high; i++){
System.out.print(nums[i]);
System.out.print(";");
}
}
public static void mergesort(int[] nums, int[] temp,int low, int high){
if(low<high){
int mid = low+(high-low)/2;
mergesort(nums,temp,low,mid);
mergesort(nums,temp,mid+1,high);
merge(nums,temp,low,mid+1,high);
}
}
public static void merge(int[] nums,int[] temp, int left, int right, int rightEnd){
int leftEnd = right-1;
int k = left;
int length = rightEnd-left + 1;
while(left<=leftEnd && right<=rightEnd){
if(nums[left]<=nums[right]){
temp[k]=nums[left];
k++;
left++;
}else{
temp[k]=nums[right];
k++;
right++;
}
}
while(left<=leftEnd){
temp[k]=nums[left];
k++;
left++;
}
while(right<=rightEnd){
temp[k++]=nums[right++];
}
for(int i=0; i<length; i++){
nums[rightEnd]=temp[rightEnd];
rightEnd--;
}
}
}