归并排序(非递归实现)

2021-02-01 19:14

阅读:467

标签:最大   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 // 生成随机数组
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 return;
}
int mergeSize = 1;
int size = arr.length;
while (mergeSize int l = 0;
while (l 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 }
}

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 help[index++] = arr[po1] }
while (po1 help[index++] = arr[po1++];
}
while (po2 help[index++] = arr[po2++];
}
for (int i = 0; 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[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 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 if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}

}

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

归并排序(非递归实现)

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

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


评论


亲,登录后才可以留言!