java算法----排序----(5)归并排序

 package log;

 import java.util.Arrays;

 public class Test4 {

     /**
* java算法---归并排序
*
* @param args
*/
public static void main(String[] args) {
// 需要排序的数组
int arr[] = { 49, 20, 36, 51, 18, 94, 61, 31, 50 };
// 循环输出该数组内容
System.out.println("排序之前:");
for (int a : arr) {
System.out.print(a + "\t");
}
System.out.println(); sort(arr, 0, arr.length - 1);
// 循环输出该数组内容
System.out.println("排序之后:");
for (int a : arr) {
System.out.print(a + "\t");
}
System.out.println(); } public static void merge(int[] list, int left, int center, int right) {
int[] tempArr = new int[list.length];
int mid = center + 1;
int third = left;
int temp = left;
while (left <= center && mid <= right) {
if (list[left] <= list[mid]) {
tempArr[third++] = list[left++];
} else {
tempArr[third++] = list[mid++];
}
}
while (mid <= right) {
tempArr[third++] = list[mid++];
}
while (left <= center) {
tempArr[third++] = list[left++];
}
while (temp <= right) {
list[temp] = tempArr[temp++];
}
System.out.println(Arrays.toString(list));
} public static void sort(int[] list, int left, int right) {
if (left < right) {
int center = (left + right) / 2;
sort(list, left, center);
sort(list, center + 1, right);
merge(list, left, center, right);
}
} }

下面是控制台的输出结果

java算法----排序----(5)归并排序

归并排序是将两个或者两个以上有序表合并成一个新的有序表,即把带排序序列分为若干个子序列,每个子序列都是有序的。然后再把有序子序列合并为整体有序序列。

上一篇:java算法----排序----(3)冒泡排序


下一篇:批处理命令——call 和 start