集册 Java实例教程 数组合并排序

数组合并排序

欢马劈雪     最近更新时间:2020-01-02 10:19:05

510
数组合并排序

/**

 * Licensed to the Apache Software Foundation (ASF) under one or more

 * contributor license agreements.  See the NOTICE file distributed with

 * this work for additional information regarding copyright ownership.

 * The ASF licenses this file to You under the Apache License, Version 2.0

 * (the "License"); you may not use this file except in compliance with

 * the License.  You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

import java.util.Collection;

import java.util.Comparator;

/*
时代Java
*/

public class Main{

    public static <T> void mergeSort(T[] a, int fromIndex, int toIndex,

            Comparator<? super T> comp) {

        if (toIndex - fromIndex <= 1)

            return;

        getSorter(a, comp).mergeSort(fromIndex, toIndex - 1);

    }

    public static <T> void mergeSort(T[] a, Comparator<? super T> comp) {

        mergeSort(a, 0, a.length, comp);

    }

    public static <T extends Comparable<? super T>> void mergeSort(T[] a,

            int fromIndex, int toIndex) {/*来 自 nowjava.com - 时  代  Java*/

        if (toIndex - fromIndex <= 1)

            return;

        getSorter(a).mergeSort(fromIndex, toIndex - 1);

    }

    public static <T extends Comparable<? super T>> void mergeSort(T[] a) {

        mergeSort(a, 0, a.length);

    }

    private static <T> SorterTemplate getSorter(final T[] a,

            final Comparator<? super T> comp) {

        return new SorterTemplate() {

            @Override

            protected void swap(int i, int j) {

                final T o = a[i];

                a[i] = a[j];

                a[j] = o;

            }


            @Override

            protected int compare(int i, int j) {

                return comp.compare(a[i], a[j]);

            }


            @Override

            protected void setPivot(int i) {

                pivot = a[i];

            }


            @Override

            protected int comparePivot(int j) {

                return comp.compare(pivot, a[j]);

            }


            private T pivot;

        };

    }

    private static <T extends Comparable<? super T>> SorterTemplate getSorter(

            final T[] a) {

        return new SorterTemplate() {

            @Override

            protected void swap(int i, int j) {

                final T o = a[i];

                a[i] = a[j];

            
展开阅读全文