方案一:
class Merge
{
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[] temp = new int[a.length];
int mid = (a.length-1)>>1;//利用a.length-1主要是考虑了a.length为奇数和偶数时计算结果是相同的
int left = 0;//数组的开始的Index
int right = a.length-1;//数组结束的Index
int leftIndex = 0;//i用来表示数组a左半边元素的index
int rightIndex = mid+1;//用rightIndex表示右半部分的元素的Index
int tempIndex = 0;//表示临时数组的元素;
while ((leftIndex<=mid)&&(rightIndex<=right))
{
if (a[leftIndex]<a[rightIndex])
{
temp[tempIndex] = a[leftIndex];
leftIndex++;
}
else
{
temp[tempIndex] = a[rightIndex];
rightIndex++;
}
tempIndex++;
}
if (leftIndex>mid)
{
for (;rightIndex<=right ;rightIndex++,tempIndex++ )
{
temp[tempIndex] = a[rightIndex];
}
}
else
{
for (;leftIndex<=mid;leftIndex++,tempIndex++ )
{
temp[tempIndex] = a[leftIndex];
}
}
//a = temp;
for (int l = 0;l<temp.length ;l++ )
{
if (l==0)
{
System.out.print("{"+temp[l]+",");
}
else if (l<temp.length-1)
{
System.out.print(temp[l]+",");
}
else
System.out.println(temp[l]+"}");
}
}
}
方案二:
class Merge
{
public static void main(String[] args)
{
int[] a = new int[]{3,44,38,5,47,15,36,26};
int[] b = new int[]{27,2,46,4,19,50,48};
int[] c = new int[a.length+b.length];
int i=0,j=0,t=0;
while ((i<a.length)&&(j<b.length))
{
if (a[i]<b[j])
{
c[t]=a[i];
i++;
}
else
{
c[t] = b[j];
j++;
}
t++;
}
if (i==a.length)
{
for (;j<b.length;j++,t++ )
{
c[t]=b[j];
}
}
else
{
for (;i<b.length ;i++,t++ )
{
c[t]=a[i];
}
}
for (int l = 0;l<c.length ;l++ )
{
if (l==0)
{
System.out.print("{"+c[l]+",");
}
else if (l<c.length-1)
{
System.out.print(c[l]+",");
}
else
System.out.println(c[l]+"}");
}
}
}*/
Merge
最新推荐文章于 2023-09-18 20:28:16 发布