合并两个数组的思路
只要从比较二个数列的第一个数,谁小就先取谁,取了后就在对应数列中删除这个数。然后再进行比较,如果有数列为空,那直接将另一个数列的数据依次取出即可。
举个简单而具体的例子,增加理解:
a[] = {50, 100};
b[] = {1 , 202};
c[] = {};
1. 比较a[0]和b[0] 发现a[0]>b[0] 取更小的 1 所以c[0] = 1;
2.比较a[0]和b[1] 发现a[0]<b[1] 取更小的 50 所以c[1] = 50;
3.比较a[1]和b[1] a[1]<b[1] 取更小的 100 所以c[2] = 100;
4.剩下b[1] 没人和他比了,添加到数组c[] 的末尾,所以c[3] = 202;
排序完毕 c[] = {1,50,100,202}
下面是代码实现:
package com.chenjun.alg;
public class MergeArray
{
public static void main(String[] args)
{
int a[] = { 1, 5, 7, 11, 22, 44, 77, 99 };
int b[] = { 2, 3, 9, 17, 21, 45, 67, 88, 100, 201 };
int c[] = mergeArr(a, b);
for (int i = 0; i < c.length; i++)
{
System.out.print(c[i] + ",");
}
}
static int[] mergeArr(int[] a, int[] b)
{
int cSize = a.length + b.length;
int c[] = new int[cSize];
int i, j, k;
i = j = k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
c[k++] = a[i++];
else
c[k++] = b[j++];
}
// a和b长度不一致 ,剩余了元素进行处理
while (i < a.length)
{
c[k++] = a[i++];
}
while (j < b.length)
{
c[k++] = b[j++];
}
return c;
}
}
输出结果
可以看出合并有序数列的效率是比较高的,可以达到O(n)。
解决了上面的合并有序数列问题,再来看归并排序,其的基本思路就是将数组分成二组A,B,如果这二组组内的数据都是有序的,那么就可以很方便的将这二组数据进行排序。如何让这二组组内数据有序了?
可以将A,B组各自再分成二组。依次类推,当分出来的小组只有一个数据时,可以认为这个小组组内已经达到了有序,然后再合并相邻的二个小组就可以了。这样通过先递归的分解数列,再合并数列就完成了归并排序
完整程序:
package com.chenjun.alg;
public class MergeSort
{
public static void main(String[] args)
{
int a[] = {100,0,5,7,9,6,3,99,98,97,54,21,45,68,78,46,21,31,6,76,83};
int len = a.length;
int[] temp = new int[len];
mergeSort(a, 0, a.length - 1, temp);
for (int i = 0; i < a.length; i++)
{
System.out.print(temp[i] + " , ");
}
}
public static 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); //再将二个有序数列合并
}
else
{
return;
}
}
public static void mergeArray(int[] a, int first, int mid, int last, int[] temp)
{
int i = first;
int m = mid;
int j = mid + 1;
int 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];
}
}
}
结果: