Java 数据结构 - 归并排序
归并排序是一种基于分治技术的排序技术。其最坏时间复杂度为 Ο(n log n),是备受推崇的算法之一。
归并排序首先将数组分成相等的两半,然后以排序的方式合并它们。
算法
归并排序不断将列表分成相等的两半,直到无法再分割为止。根据定义,如果列表中只有一个元素,则该列表已排序。然后,归并排序合并较小的已排序列表,同时保持新列表也已排序。
Step 1: if it is only one element in the list it is already sorted, return. Step 2: divide the list recursively into two halves until it can no more be divided. Step 3: merge the smaller lists into new list in sorted order.
示例
import java.util.Arrays; public class MergeSort { int[] array = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 }; public void merge(int low, int mid, int high) { int l1, l2, i, b[] = new int[array.length]; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(array[l1] <= array[l2]) { b[i] = array[l1++]; } else b[i] = array[l2++]; } while(l1 <= mid) { b[i++] = array[l1++]; } while(l2 <= high) { b[i++] = array[l2++]; } for(i = low; i <= high; i++) { array[i] = b[i]; } } public void sort(int low, int high) { int mid; if(low < high) { mid = (low + high) / 2; sort(low, mid); sort(mid+1, high); merge(low, mid, high); } else { return; } } public static void main(String args[]) { MergeSort obj = new MergeSort(); int max = obj.array.length-1; System.out.println("Contents of the array before sorting : "); System.out.println(Arrays.toString(obj.array)); obj.sort(0, max); System.out.println("Contents of the array after sorting : "); System.out.println(Arrays.toString(obj.array)); } }
输出
[10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0] Contents of the array after sorting : [0, 10, 14, 19, 26, 27, 31, 33, 35, 42, 44]
广告