使用非递归的方式实现归并排序
话不多说,直接上代码:
public class MergySort {
public static void main(String[] args) {
int[] nums = {38, 27, 43, 3, 9, 82, 10};
int[] sortedArray = MergySort.mergySort(nums);
// 输出排序后的数组
for (int num : sortedArray) {
System.out.print(num + " ");
}
}
public static int[] mergySort(int[] nums) {
int n = nums.length;
Queue<int[]> queue = new LinkedList<>();
int[] ans ;
for (int i = 0;i < n;i++) {
queue.offer(new int[]{nums[i]});
}
while(queue.size() > 1) {
int[] arr1 = queue.poll();
int[] arr2 = queue.poll();
int[] tmp = mergy(arr1,arr2);
queue.offer(tmp);
}
ans = queue.poll();
return ans;
}
public static int[] mergy(int[] arr1,int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;
int ptr1 = 0;
int ptr2 = 0;
int ansPtr = 0;
int[] ans = new int[n1+n2];
while(ptr1 < n1 && ptr2 < n2) {
if (arr1[ptr1] <= arr2[ptr2]) {
ans[ansPtr++] = arr1[ptr1++];
} else {
ans[ansPtr++] = arr2[ptr2++];
}
}
while(ptr1 < n1) {
ans[ansPtr++] = arr1[ptr1++];
}
while(ptr2 < n2) {
ans[ansPtr++] = arr2[ptr2++];
}
return ans;
}
}
基本思路是模拟我们递归实现归并的过程,大家可以把它理解成是一个自底向上的调用过程,用一个队列来模拟过程:
整个过程其实也是类似于广搜的过程。