简单实现MergeSort

public class MergeSort {

public static void main(String[] args) {

MergeSort ms = new MergeSort();
// int[] a = ms.merge(3, 2);
// a = ms.merge(2, 3);

int[] b = { 1, 2, 3, 4, 5, 6 };
int[] c = { 4, 5, 6, 7, 6, 354, 7542, 61, 34, 67, 8, 3, 4, 8, 1, 4, 6,
89, 2, 3, 4, 7, 234, 545, 2, 34, 8 };
long start = System.currentTimeMillis();
c = ms.sort(c);
long end = System.currentTimeMillis();
System.out.println("MergeSort a array with lenght of " + c.length
+ " in " + (end - start) + " second");
for (int i = 0; i < c.length; i++) {
System.out.println(c[i]);
}

}

private int[] sort(int[] number) {
int dividPoint = number.length / 2;// 4-2 5-2;
// int secondPart = firstPart+1;

int[] sortedArray = null;
int[] firstArray = getArray(number, 0, dividPoint);
int[] secondArray = getArray(number, dividPoint, number.length);

// secondArray = divid(secondArray);

if (firstArray.length > 2) {
firstArray = sort(firstArray);
} else if (firstArray.length <= 2) {
firstArray = merge(firstArray);
}

if (secondArray.length > 2) {
secondArray = sort(secondArray);
} else if (secondArray.length <= 2) {
secondArray = merge(secondArray);
}
sortedArray = merge(firstArray, secondArray);

return sortedArray;
}

private int[] getArray(int[] arr, int start, int end) {
int[] subArray = new int[end - start];
int subindex = 0;
for (int index = start; index < end; index++) {
subArray[subindex] = arr[index];
subindex++;
}
return subArray;
}


private int[] merge(int i, int j) {
int[] array = new int[2];
if (i > j) {
array[0] = j;
array[1] = i;
} else {
array[0] = i;
array[1] = j;
}
return array;
}

private int[] merge(int[] i) {
int[] returnArr = null;
if (i.length == 1) {
returnArr = merge(i[0]);
}
if (i.length == 2) {
returnArr = merge(i[0], i[1]);
}
return returnArr;
}

private int[] merge(int i) {
int[] array = new int[1];
array[0] = i;
return array;
}


private int[] merge(int[] i, int[] j) {
int[] array = new int[i.length + j.length];
int pointi = 0;
int pointj = 0;
for (int index = 0; index < array.length; index++) {
if (pointi < i.length && pointj < j.length) {
if (i[pointi] <= j[pointj]) {
array[index] = i[pointi];
pointi++;
} else {
array[index] = j[pointj];
pointj++;
}
} else {
if (pointi == i.length && pointj < j.length) {
int addedIndex = i.length + pointj - 1;
for (int newIndex = addedIndex + 1; newIndex < array.length; newIndex++) {
array[newIndex] = j[pointj];
pointj++;
}
break;
}
if (pointi < i.length && pointj == j.length) {
int addedIndex = j.length + pointi - 1;
for (int newIndex = addedIndex + 1; newIndex < array.length; newIndex++) {
array[newIndex] = i[pointi];
pointi++;
}
break;
}
}

}

return array;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值