本文共 2172 字,大约阅读时间需要 7 分钟。
归并排序是一个高效的排序算法,通过分而治之的思想将问题分解成更小的子问题。归并排序的时间复杂度为O(n log n),空间复杂度为O(n),并且算法本身是稳定的。
以下是归并排序的递归实现:
public class mergeTest { public static void mergeSort(int[] array) { mergeSort(array, 0, array.length - 1); } private static void mergeSort(int[] array, int low, int high) { if (low >= high) { return; } int mid = (low + high) / 2; mergeSort(array, low, mid); mergeSort(array, mid + 1, high); merge(array, low, mid, high); } public static void merge(int[] array, int low, int mid, int high) { int s1 = low; int s2 = mid + 1; int[] tempArray = new int[high - low + 1]; int i = 0; while (s1 <= mid && s2 <= high) { if (array[s1] <= array[s2]) { tempArray[i++] = array[s1++]; } else { tempArray[i++] = array[s2++]; } } while (s1 <= mid) { tempArray[i++] = array[s1++]; } while (s2 <= high) { tempArray[i++] = array[s2++]; } for (int j = 0; j < tempArray.length; j++) { array[low + j] = tempArray[j]; } }} 以下是归并排序的非递归实现:
public class mergeTest1 { public static void mergeSort(int[] array) { for (int i = 1; i < array.length; i *= 2) { merge(array, i); } } public static void merge(int[] array, int gap) { int[] tempArray = new int[array.length]; int k = 0; int s1 = 0; int e1 = s1 + gap - 1; int s2 = e1 + 1; int e2 = s2 + gap - 1; while (s1 < e1 && s2 < e2) { if (array[s1] <= array[s2]) { tempArray[k++] = array[s1++]; } else { tempArray[k++] = array[s2++]; } } while (s1 < e1) { tempArray[k++] = array[s1++]; } while (s2 < e2) { tempArray[k++] = array[s2++]; } for (int i = 0; i < array.length; i++) { array[i] = tempArray[i]; } }} 这两个实现都采用了归并排序的思想,通过合并有序的小段来得到最终的有序数组。递归实现的代码更为直观,但需要注意递归深度的问题。大多数编程语言都对递归深度有限制,超过限制会导致栈溢出。因此在实际应用中,需要小心合理选择排序的输入规模。非递归实现避免了这个问题,但代码结构稍微复杂一些,需要显式地管理多段数组的合并过程。
转载地址:http://tbrnz.baihongyu.com/