mergesort java 源码_MergeSort(Java)

mergesort java 源码_MergeSort(Java)实现代码:MergeSort.javapublicclassMergeSort{publicint[]sort(int[]input){if(input.length<=1)returninput;if(input.length==2){if(input[0]>input[1]){inttemp=input[0];input[0]=in…

实现代码:MergeSort.java

public class MergeSort {

public int[] sort(int[] input) {

if (input.length <= 1) return input;

if (input.length == 2) {

if (input[0] > input[1]) {

int temp = input[0];

input[0] = input[1];

input[1] = temp;

}

return input;

}

int mid = input.length / 2;

int[] firstHalf = sort(getPart(input, 0, mid));

int[] secondHalf = sort(getPart(input, mid + 1, input.length – 1));

return mergePart(firstHalf, secondHalf);

}

private int[] mergePart(int[] firstHalf, int[] secondHalf) {

int[] result = new int[firstHalf.length + secondHalf.length];

int firstIndex = 0, secondIndex = 0, resultIndex = 0;

while (resultIndex < result.length) {

if (chooseFirstHalf(firstHalf, firstIndex, secondHalf, secondIndex))

result[resultIndex++] = firstHalf[firstIndex++];

else

result[resultIndex++] = secondHalf[secondIndex++];

}

return result;

}

private boolean chooseFirstHalf(int[] firstHalf, int firstIndex, int[] secondHalf, int secondIndex) {

if (firstIndex == firstHalf.length) return false;

if (secondIndex == secondHalf.length) return true;

return firstHalf[firstIndex] < secondHalf[secondIndex];

}

private int[] getPart(int[] input, int begin, int end) {

int[] result = new int[end – begin + 1];

for (int i = begin; i <= end; i++) result[i – begin] = input[i];

return result;

}

}

测试代码:MergeSortTest.java

import org.junit.*;

import static org.junit.Assert.*;

public class MergeSortTest {

MergeSort mergeSort;

@Before

public void setUp() {

mergeSort = new MergeSort();

}

@Test

public void should_return_1_for_merge_sort_1() {

int[] input = {1};

int[] expected = {1};

assertArrayEquals(expected, mergeSort.sort(input));

}

@Test

public void should_return_12_for_merge_sort_21() {

int[] input = {2,1};

int[] expected = {1,2};

assertArrayEquals(expected, mergeSort.sort(input));

}

@Test

public void should_return_1234_for_merge_sort_3214() {

int[] input = {3,2,1,4};

int[] expected = {1,2,3,4};

assertArrayEquals(expected, mergeSort.sort(input));

}

@Test

public void should_return_12345_for_merge_sort_54321() {

int[] input = {5, 4, 3, 2, 1};

int[] expected = {1, 2, 3, 4, 5};

assertArrayEquals(expected, mergeSort.sort(input));

}

}

今天的文章mergesort java 源码_MergeSort(Java)分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/5742.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注