parent
cd82a1e088
commit
d9a8742b66
@ -0,0 +1,61 @@
|
||||
/*
|
||||
* To change this license header, choose License Headers in Project Properties.
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* @author lenovo
|
||||
*/
|
||||
public class MergeSort {
|
||||
|
||||
private static int[] aux;
|
||||
|
||||
public static void merge(int[] a, int low, int mid, int high)
|
||||
{
|
||||
int i = low;
|
||||
int j = mid + 1;
|
||||
|
||||
for(int k=low; k<=high; k++)
|
||||
{
|
||||
aux[k] = a[k];
|
||||
}
|
||||
|
||||
for(int k=low; k<=high; k++)
|
||||
{
|
||||
if(i>mid)
|
||||
{
|
||||
a[k] = aux[j++];
|
||||
}
|
||||
else if(j > high)
|
||||
{
|
||||
a[k] = aux[i++];
|
||||
}
|
||||
else if (aux[j] < aux[i])
|
||||
{
|
||||
a[k] = aux[j++];
|
||||
}
|
||||
else
|
||||
{
|
||||
a[k] = aux[i++];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void sort(int[] a, int low, int high)
|
||||
{
|
||||
if(high <= low) return;
|
||||
|
||||
int mid = low + (high - low) / 2;
|
||||
sort(a, low, mid);
|
||||
sort(a, mid+1, high);
|
||||
merge(a, low, mid, high);
|
||||
}
|
||||
public void sort(int[] a)
|
||||
{
|
||||
int length = a.length;
|
||||
aux = new int[length];
|
||||
sort(a, 0, length-1);
|
||||
}
|
||||
}
|
Loading…
Reference in new issue