首页 > 代码库 > 归并排序
归并排序
它的思想是将一个无序的数组先用递归进行二分,当分解为无限小时,即为单个整数时,再对其进行排列。得出有序的数组
代码如下:
package com.jll.sort;
public class MergeSort {
public MergeSort() {
}
public void merge(int[] a, int start, int finish) {
if (start == finish)
return;
else {
int mid = (start + finish) / 2;
merge(a, start, mid);
merge(a, mid + 1, finish);
sort(a, start, mid+1 , finish);
}
}
public void sort(int[] a, int begin, int mid, int end) {
int middle = mid - 1;
int low = begin;
int high = end;
int b[] = new int[a.length];
int count = 0;
while (begin <= middle && mid <= end) {
if (a[begin] <= a[mid]){
b[count++] = a[begin++];
} else {
b[count++] = a[mid++];
}
}
while (begin <= middle) {
b[count++] = a[begin++];
}
while (mid <= end) {
b[count++] = a[mid++];
}
for (int i = low; i <= high; i++) {
a[i] = b[i-low];
}
}
public static void main(String[] args) {
MergeSort ms = new MergeSort();
int a[] = new int[10];
for (int i = 0; i < 10; i++) {
a[i] = (int) (Math.random() * 100 + 1);
}
System.out.println("a:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
ms.merge(a, 0, 9);
System.out.println();
System.out.println("a:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
里面的代码需要仔细看才能明白其中的道理