## 归并排序 原

沧海一刀

合并两个数组的思路

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;

``````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;
}
}
``````

``````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];
}
}
}
``````

### 评论(1)

#### 暂无文章

linuxCool
50分钟前
15
0
Python程序员需要知道的30个技巧

1 直接交换两个数字位置 1x, y = 10, 202print(x, y)3x, y = y, x4print(x, y)5#1 (10, 20)6#2 (20, 10) 2 比较运算符的链接 1n = 102result = 1 < n < 203print(result)4# True5result = 1 ......

50分钟前
10
0

honeymose

10
0
Android :报错Your project path contains non-ASCII characters.

lanyu96

7
0
Nginx平滑添加模块

Nginx已经编译安装并运行了一段时间, 然后某一天, 发现需要用到某个模块但当初没有编译, 这个时候怎么办呢? 卸载重新安装肯定可以的, 如果Nginx版本没有变更的话, 则有一个相对平滑的方法来添...

11
0