-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
45 lines (41 loc) · 935 Bytes
/
Copy pathMergeSort.java
File metadata and controls
45 lines (41 loc) · 935 Bytes
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
package sort;
public class MergeSort {
public int[] sort(int[] a,int left,int right)
{
if(left < right)
{
int mid = (left+right)/2;
sort(a,left,mid);
sort(a,mid+1,right);
merge(a,left,mid,right);
}
return a;
}
public void merge(int[] a, int left, int mid, int right)
{
int[] temp = new int[right-left+1];
int i = left;
int j = mid+1;
int t = 0;//临时数组指针
while(i<=mid&&j<=right)
{
if(a[i] < a[j])
{
temp[t++] = a[i++];
}else{
temp[t++] = a[j++];
}
}
while(i<=mid)
{
temp[t++] = a[i++];
}
while(j<=right)
{
temp[t++] = a[j++];
}
t = 0;
while(left<=right)
a[left++] = temp[t++];
}
}