-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
50 lines (41 loc) · 1.18 KB
/
Copy pathMergeSort.java
File metadata and controls
50 lines (41 loc) · 1.18 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
package com.wgcris.LeetcodeAlgorithm;
public class MergeSort {
//Ïȵݹé·Ö½â Ôٺϲ¢ÐòÁÐ
public void mergeSort(int[] a,int first,int last,int temp[])
{
if(first<last)
{
int mid=(first+last)/2;
mergeSort(a,first,mid,temp);
mergeSort(a,mid+1,last,temp);
mergearray(a,first,mid,last,temp);
}
}
public void mergearray(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
public static void main(String[] args) {
MergeSort m=new MergeSort();
int[] a={5,4,8,1,2,3,4,5,7,6,4,1,5};
int[] temp=new int[a.length];
m.mergeSort(a, 0, a.length-1, temp);
for(int i:a)
System.out.print(i+" ");
}
}