Java examples for Collection Framework:Array Sort
Array merge Sort
/**// w w w . j a v a2 s . c om * 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; 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) { 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]; a[j] = o; } @Override protected int compare(int i, int j) { return a[i].compareTo(a[j]); } @Override protected void setPivot(int i) { pivot = a[i]; } @Override protected int comparePivot(int j) { return pivot.compareTo(a[j]); } private T pivot; }; } }