码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序(非递归实现)

时间:2020-05-01 13:09:11      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:最大   int   static   ret   数组   rand   out   str   print   


import java.util.Arrays;

/**
* 归并排序(非递归实现)
*/
public class MergeSort2 {

public static void main(String[] args) {
// 测试次数
int times = 50000;

int maxNum = 100;
int maxSize = 100;
for (int i = 0; i < times; i++) {
// 生成随机数组
int[] arr1 = generateArray(maxNum, maxSize);
// 复制
int[] arr2 = copyArray(arr1);
// 归并排序
mergeSort(arr1);
// Api排序
Arrays.sort(arr2);
// 比较排序结果
if (!arrayEquals(arr1, arr2)) {
System.out.println("Sort failed!!! at " + i);
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
return;
}
}
System.out.println("Sort success");
}

public static void mergeSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
int mergeSize = 1;
int size = arr.length;
while (mergeSize < size) {
int l = 0;
while (l < size) {
int mid = l + mergeSize - 1;
if (mid >= size) {
break;
}
int r = Math.min(mid + mergeSize, size - 1);
merge(arr, l, mid, r);
l = r + 1;
}
if (mergeSize > (size >> 1)) {
break;
}
mergeSize <<= 1;
}
}

public static void merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int index = 0;
int po1 = left;
int po2 = mid + 1;
while (po1 <= mid && po2 <= right) {
help[index++] = arr[po1] < arr[po2] ? arr[po1++] : arr[po2++];
}
while (po1 <= mid) {
help[index++] = arr[po1++];
}
while (po2 <= right) {
help[index++] = arr[po2++];
}
for (int i = 0; i < help.length; i++) {
arr[left + i] = help[i];
}
}

/**
* 生成随机数组
*
* @param maxNum 最大数
* @param maxSize 数组最大大小
* @return 随机数组
*/
private static int[] generateArray(int maxNum, int maxSize) {
int[] arr = new int[(int) (maxSize * Math.random())];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (maxNum * Math.random()) - (int) (maxNum * Math.random());
}
return arr;
}

/**
* 复制数组
*
* @param arr 要复制的数组
* @return 复制的数组
*/
private static int[] copyArray(int[] arr) {
if (arr == null) {
return null;
}
int[] copy = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
copy[i] = arr[i];
}
return copy;
}

/**
* 判断两数组是否完全相同
*
* @param arr1 数组1
* @param arr2 数组2
* @return 是否相同
*/
private static boolean arrayEquals(int[] arr1, int[] arr2) {
if (arr1 == arr2) {
return true;
}
if (arr1 == null || arr2 == null || arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr1.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}

}

/* 如有错误,欢迎批评指正 */

归并排序(非递归实现)

标签:最大   int   static   ret   数组   rand   out   str   print   

原文地址:https://www.cnblogs.com/laydown/p/12813066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!