主代码
package sort;
/**
* 归并排序
* @author potter
*
*/
public class Guibingsort {
//low代表数组的第一个数字的下标一般为0;
//mid代表数组中间点的位置
//mid+1代表从中间点分开右边数组的第一个位置的下标
//hight代表数组的最大下标值
public static void merge(int[] a,int low, int mid, int hight){
int[] temp = new int[hight - low +1];
int i = low;
int j = mid + 1;
int k = 0;
//把较小的数移入到新数组中
while (i <= mid && j <= hight) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
}else {
temp[k++] = a[j++];
}
}
//把左边剩余的数组移入数组
while (i <= mid) {
temp[k++] = a[i++];
}
//把右边剩余的数组移入数组
while (j <= hight) {
temp[k++] = a[j++];
}
for(int x = 0;x < temp.length;x++){
a[x+low] = temp[x];
}
}
public static int[] sort(int[] a,int low,int hight) {
int mid = (low+hight)/2;
if (low < hight) {
sort(a, low, mid);
sort(a, mid+1, hight);
merge(a, low, mid, hight);
}
return a;
}
}
随机生成数组
package utilsort;
import java.util.Random;
/**
* 随机生成数组
* @author Administrator
*
*/
public class UtilsSort {
static Random r = new Random();
//length代表数组长度
//min代表可以随机生成数组的最小值
//max代表可以随机生成数组的最大值
public static int[] creat(int length,int min,int max){
if (min > max) {
int temp = min;
min = max;
max = temp;
}
int arr[] = new int[length];
for (int i = 0; i < length; i++) {
int nextInt = r.nextInt(max);
arr[i] = nextInt + min ;
}
return arr;
}
}
遍历输出类
package utilsort;
public class PrintUtils {
public static void printarr(int[] arr){
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}
测试类
package sort;
import utilsort.PrintUtils;
import utilsort.UtilsSort;
public class Testsort {
public static void main(String[] arg) {
int[] arr = UtilsSort.creat(5, 1, 33);
System.out.println("排序前的数列");
PrintUtils.printarr(arr);
Guibingsort.sort(arr, 0, arr.length-1);
System.out.println("排序后的数列");
PrintUtils.printarr(arr);
}
}