forked from 5zhu/algorithm-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
60 lines (55 loc) · 1.32 KB
/
Copy pathMergeSort.java
File metadata and controls
60 lines (55 loc) · 1.32 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 com.algorithdemo.sort;
public class MergeSort {
public static void main(String[] args) {
int[] array = {3,5,7,2,6,1,3,8,4};
mergeSort(array, 0, array.length - 1);
for (int i : array) {
System.out.println(i);
}
}
/**
* šé˛˘ĹĹĐň O(nlogn)
* @param array
* @param l
* @param r
*/
public static void mergeSort(int[] array, int l, int r){
if(l == r){
return;
}
int m = (l + r)/2;
mergeSort(array, l, m);
mergeSort(array, m+1, r);
mergeArray(array, l, m, r);
}
/**
* şĎ˛˘Ęý×é
* @param array
* @param l
* @param m
* @param r
*/
public static void mergeArray(int[] array, int l, int m, int r){
int [] temp = new int[r - l + 1];
int i = l;
int j = m + 1;
int k = 0; //temp ĎÂąę
while(i <= m && j <= r){
if(array[i] < array[j]){
temp[k++] = array[i++];
}else{
temp[k++] = array[j++];
}
}
//
while(i <= m){
temp[k++] = array[i++];
}
while(j <= r){
temp[k++] = array[j++];
}
for (int x = 0, y = l; x < temp.length; x++, y++) {
array[y] = temp[x];
}
}
}