集册 Java实例教程 数组快速排序

数组快速排序

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

488
数组快速排序

/**

 * 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.

 *//*时 代 J a v a - nowjava.com*/

import java.util.Collection;

import java.util.Comparator;


public class Main{

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

            Comparator<? super T> comp) {

        if (toIndex - fromIndex <= 1)

            return;

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

    }

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

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

    }

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

            int fromIndex, int toIndex) {

        if (toIndex - fromIndex <= 1)

            return;

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

    }/*from n o w    j a v a  . c o m*/

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

        quickSort(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];

         
展开阅读全文