<pre name="code" class="java">package com;
/**
*
* @author yanshuai
*
*/
public class MyMergeSort {
/**
* 合并两个有序数组
*/
public static int[] mergeTwoArray(int[] a, int[] b){
int i = 0, j = 0, k = 0,
aLength = a.length,
bLength = b.length;
int[] temp = new int[aLength + bLength];
while (i < aLength && j < bLength) {
if (a[i] < b[j]){
temp[k++] = a[i++];
} else {
temp[k++] = b[j++];
}
}
while ( i < aLength) {
// copy a 剩余的
temp[k++] = a[i++];
}
while ( j < bLength) {
// copy b 剩余的
temp[k++] = b[j++];
}
return temp;
}
/**
* 合并三个有序数组
*/
public static int[] mergeThreeArray(int[] a, int[] b, int[] c){
int i = 0, j = 0, k = 0, t = 0,
aLength = a.length,
bLength = b.length,
cLength = c.length;
int[] temp = new int[aLength + bLength + cLength];
while (i < aLength && j < bLength && k < cLength) {
if (a[i] < b[j] && a[i] < c[k]){
temp[t++] = a[i++];
} else if ( b[j] < c[k]) {
temp[t++] = b[j++];
} else {
temp[t++] = c[k++];
}
} // 合并完三个数组中最短的
// 1 2路没有合并完
while (i < aLength && j < bLength) {
if (a[i] < b[j]){
temp[t++] = a[i++];
} else {
temp[t++] = b[j++];
}
}
// 1 3 路没有合并完
while (i < aLength && k < cLength) {
if (a[i] < c[j]){
temp[t++] = a[i++];
} else {
temp[t++] = c[j++];
}
}
// 2 3 路没有合并完
while (j < bLength && k < cLength) {
if (b[i] < c[j]){
temp[t++] = b[i++];
} else {
temp[t++] = c[j++];
}
}
// 1路没有合并完
while ( i < aLength) {
temp[t++] = a[i++];
}
// 2路没有合并完
while ( j < bLength) {
temp[t++] = b[j++];
}
// 3路没有合并完
while ( k < cLength) {
temp[t++] = c[k++];
}
return temp;
}
}
归并排序在数据库 外排算法中有重要应用, 当一次排序内存不够用时, 需要分批加载并生成临时数据表,然后对多个有序的临时表进行合并