Description

shuffle

License

Apache License

Declaration

public static <A> List<A> shuffle(List<A> as) 

Method Source Code

//package com.java2s;
/*/*from   w  w  w  .  j  ava2s  . c om*/
 * Copyright 2012 Andy Boothe
 *
 *   Licensed 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.Comparator;

import java.util.List;

import java.util.Random;

public class Main {
    public static <A> List<A> shuffle(List<A> as) {
        final Random rand = new Random();
        return qsort(as, new Comparator<A>() {
            public int compare(A a, A b) {
                return rand.nextInt(3) - 1;
            }
        });
    }

    public static <A extends Comparable<A>> List<A> qsort(List<A> as) {
        return qsort(as, new Comparator<A>() {
            public int compare(A a, A b) {
                return a.compareTo(b);
            }
        });
    }

    public static <A> List<A> qsort(List<A> as, Comparator<A> comp) {
        return qsort2(as, 0, as.size(), comp);
    }

    private static <A> List<A> qsort2(List<A> xs, int low, int high, Comparator<A> comp) {
        //       System.out.println("low="+low+", high="+high);
        if (high - low <= 1)
            ; // We're already sorted, trivially
        else {
            int low0 = low, high0 = high;
            A pivot = xs.get(low), t;
            low = low + 1;
            while (low != high) {
                //              System.out.println("    low="+low+", high="+high);
                if (comp.compare(xs.get(low), pivot) < 0)
                    low = low + 1;
                else {
                    high = high - 1;
                    A tp = xs.get(high);
                    xs.set(high, xs.get(low));
                    xs.set(low, tp);
                }
            }
            t = xs.get(low0);
            xs.set(low0, xs.get(low - 1));
            xs.set(low - 1, t);
            qsort2(xs, low0, low - 1, comp);
            qsort2(xs, low, high0, comp);
        }
        return xs;
    }
}

Related

  1. Shuffle(int[] v)
  2. shuffle(Integer[] data)
  3. shuffle(List list)
  4. shuffle(List list)
  5. shuffle(List list, Random rnd)
  6. shuffle(List list)
  7. shuffle(List list)
  8. shuffle(List list, int nswaps)
  9. shuffle(Object[] a)