class Merge
{
private static int[] aux;//定义一个数组用于存储归并时存储原数组
public static void sort(int[] a)
{
aux = new int[a.length];//将数组aux的长度定义为与原数组的长度是一样的
sort(a ,0, a.length-1);//将原数组进行划分
}
public static void sort(int[] a,int low,int high)
{
if (high<=low)//如果子数组中长度为1,此时就不再进行sort了
{
return;
}
int mid =low+ (high-low)/2;//定义一个中位数
sort(a ,low,mid);//将a数组中的元素的前一半尽心再次sort
sort(a ,mid+1,high);//将数组的后一半进行sort
merge(a,low,mid,high);//将数组的前一半和后一半进行一个merge
}
public static void merge(int[] a,int low,int mid,int high)
{
int leftIndex = low;//定义前一半数组元素的Index
int rightIndex = mid+1;//定义后一半元素的Index
int tempIndex =low;//定义当前子数组的起始位置元素的Index
for (int i =low;i<=high ;i++ )//将元素组a的元素复制到数组啊aux中
{
aux[i] = a[i];
}
while ((leftIndex<=mid)&&(rightIndex<=high))//实现归并
{
if (aux[leftIndex]<aux[rightIndex])
{
a[tempIndex] = aux[leftIndex];
leftIndex++;
}
else
{
a[tempIndex] = aux[rightIndex];
rightIndex++;
}
tempIndex++;
}
if (leftIndex>mid)
{
for (;rightIndex<=high;rightIndex++,tempIndex++)
{
a[tempIndex] = aux[rightIndex];
}
}
else
{
for (;leftIndex<=mid;leftIndex++,tempIndex++ )
{
a[tempIndex] = aux[leftIndex];
}
}
}
public static void printArr(int[] a)//输出数组
{
for (int i=0;i<a.length ;i++ )
{
if (i==0)
{
System.out.print("{"+a[i]+",");
}
else if (i<a.length-1)
{
System.out.print(a[i]+",");
}
else
System.out.println(a[i]+"}");
}
}
}
class MergeSort
{
public static void main(String[] args)
{
int[] a = new int[]{3,44,38,5,47,15,36,26,27,2,46,4,19,50,48};
int[] aux = new int[a.length];
Merge.sort(a);
Merge.printArr(a);
}
}
MergeSort
最新推荐文章于 2024-03-13 19:46:50 发布