归并排序

作者: 就这些吗 | 来源:发表于2020-01-01 03:08 被阅读0次
    public class MergeSort {
    
        public static void mergeSort(int array[], int start, int end) {
            if (start >= end) {
                return;
            }
            int mid = (end - start) / 2 + start;
            mergeSort(array, start, mid);
            mergeSort(array, mid + 1, end);
            merge(array, start, mid, end);
        }
    
        public static void merge(int array[], int start, int mid, int end) {
    
            int length = end - start + 1;
            int temp[] = new int[length];
            int left = start;
            int mid1 = mid + 1;
            int i = 0;
            while (left <= mid && mid1 <= end) {
                if (array[left] < array[mid1]) {
                    temp[i++] = array[left++];
                } else {
                    temp[i++] = array[mid1++];
                }
    
            }
    
            while (left <= mid) {
                temp[i++] = array[left++];
            }
            while (mid1 <= end) {
                temp[i++] = array[mid1++];
            }
    
            for (int n = 0; n < length; n++) {
                array[n + start] = temp[n];
            }
        }
    
        public static void main(String[] args) {
            int a[] = { 1, 51, 23, 4, 6, 9, 9, 10, 55 };
            mergeSort(a, 0, a.length - 1);
            System.out.println(Arrays.toString(a));
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:归并排序

        本文链接:https://www.haomeiwen.com/subject/gvijwctx.html