java实现归并排序算法
前面我们讲了归并排序算法,接下来我们来用java代码实现呗,如下
package ttt;
import java.util.Arrays;
public class MergeSort {
public static int[] lastMergeSort(int[] list1,int[] list2) {
int i = 0, j = 0, k = 0;
int [] temp = new int[list1.length + list2.length];
while (i < list1.length && j < list2.length) {
if (list1[i] <= list2[j]) {
temp[k++] = list1[i++];
}else {
temp[k++] = list2[j++];
}
}
if (i == list1.length) {
while(j <list2.length) {
temp[k++] = list2[j++];
}
}
if (j == list2.length) {
for(;i <list1.length;)
temp[k++] = list1[i++];
}
return temp;
}
public static int[] mergeSort(int[] theArray) {
if(theArray.length ==1) {
return theArray;
}
int mid = (int)theArray.length/2;
int[] leftArray = mergeSort(Arrays.copyOfRange(theArray, 0, mid));//前闭后开区间,这种写法开闭了很多空间,有点浪费,实则可以通过别的写法避免的
int[] rightArray = mergeSort(Arrays.copyOfRange(theArray, mid, theArray.length));
return lastMergeSort(leftArray, rightArray);
}
public static void main(String[] args) {
int []theArray = {10,1,18,30,23,12,7,5,18,17};
System.out.print("之前的排序:");
for(int i = 0; i < theArray.length; i++) {
System.out.print(theArray[i] + " ");
}
int [] larray = {1,4,10};
int [] rarray = {2,6,8,11,15,18};
// int []result_array = lastMergeSort(larray,rarray);
int []resultArray = mergeSort(theArray);
System.out.print("归并排序:");
for(int v : resultArray) {
System.out.print(v + " ");
}
}
}
运行结果如下
之前的排序:10 1 18 30 23 12 7 5 18 17 归并排序:1 5 7 10 12 17 18 18 23 30
符合预期
还没有评论,来说两句吧...