A garbage-free randomised quicksort : Random « Development Class « Java






A garbage-free randomised quicksort

  
//package com.ryanm.util;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

/**
 * A garbage-free randomised quicksort
 * 
 * @author ryanm
 */
public class QuickSort {
  private static final Random rng = new Random();

  private QuickSort() {
    // no instances
  }

  /**
   * @param <T>
   * @param array
   * @param comp
   */
  public static <T> void sort(T[] array, Comparator<T> comp) {
    sort(array, comp, 0, array.length - 1);
  }

  /**
   * @param <T>
   * @param array
   * @param comp
   * @param lo
   *            lowest index to sort
   * @param hi
   *            highest index to sort
   */
  public static <T> void sort(T[] array, Comparator<T> comp, int lo, int hi) {
    if (hi > lo) {
      // choose random element to pivot on
      int pivotIndex = rng.nextInt(hi - lo) + lo;

      // swap elements till everything smaller than the pivot lies
      // before it
      pivotIndex = partition(array, comp, lo, hi, pivotIndex);

      // recurse
      sort(array, comp, lo, pivotIndex - 1);
      sort(array, comp, pivotIndex + 1, hi);
    }
  }

  /**
   * Shuffle elements around to partially-sorted low/pivot/high order
   * 
   * @param <T>
   * @param array
   * @param comp
   * @param lo
   * @param hi
   * @param pivotIndex
   *            the starting index of the pivot element
   * @return The new index of the pivot element
   */
  private static <T> int partition(T[] array, Comparator<T> comp, int lo,
      int hi, int pivotIndex) {
    T pivot = array[pivotIndex];

    // send pivot to the back
    swap(array, pivotIndex, hi);

    // index of low/high boundary
    int index = lo;

    for (int i = lo; i < hi; i++) {
      if (comp.compare(array[i], pivot) <= 0) { // element is lower or
                            // equal to the pivot
                            // swap it to the low
                            // region
        swap(array, i, index);
        index++;
      }
    }

    swap(array, hi, index);

    return index;
  }

  /**
   * Swaps elements
   * 
   * @param <T>
   * @param array
   * @param i
   * @param j
   */
  private static <T> void swap(T[] array, int i, int j) {
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }

  /**
   * @param args
   */
  public static void main(String[] args) {
    Integer[] array = new Integer[15];
    Random rng = new Random();
    int split = 10;
    for (int i = 0; i < split; i++) {
      array[i] = new Integer(rng.nextInt(100));
    }
    for (int i = split; i < array.length; i++) {
      array[i] = null;
    }

    System.out.println(Arrays.toString(array));

    QuickSort.sort(array, new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
      };
    }, 0, split - 1);

    System.out.println(Arrays.toString(array));

  }
}

   
    
  








Related examples in the same category

1.Create random number
2.Create two random number generators with the same seed
3.Does Math.random() produce 0.0 and 1.0
4.Random numbers between 1 and 100
5.Random number between 0 AND 10
6.Random integers that range from from 0 to n
7.Random.nextInt(n) returns a distributed int value between 0 (inclusive) and n (exclusive).
8.Round Java float and double numbers using Math.round
9.Randomizer
10.nextDouble() and nextGaussian() in java.util.Random
11.Generating random numbers
12.Generate random ints by asking Random() for
13.Getting random numbers: nextGaussian
14.Generate a random array of numbers
15.Next double and next int
16.Random bytes
17.Random boolean
18.Random long type number
19.Random float type number
20.Random double type number
21.Math.random
22.A wrapper that supports all possible Random methods via the java.lang.Math#random() method and its system-wide {@link Random} object.
23.Operations for random Strings
24.Random Util with ReentrantLock
25.A Java implementation of the MT19937 (Mersenne Twister) pseudo random number generator algorithm
26.Randomizer
27.Random: Properly synchronized and can be used in a multithreaded environment
28.A predictable random number generator.
29.Random GUID
30.A random.org seeded random generator.
31.Generates a secure random word with the given length consisting of uppercase and lowercase letters and numbers.
32.A random choice maker
33.Memory-efficient map of keys to values with list-style random-access semantics.
34.Generates a random integer inside the lo and hi interval
35.Randomizer
36.RandomGUID generates truly random GUIDs
37.A random access text file allows a text file to be accessed randomly starting at any position.
38.A linear random method based on xor shifts
39.Mersenne Twister Random
40.A GaussianHat is a random number generator that will give you numbers based on a population mean and standard deviation.
41.Randomly permutes the elements of the specified array
42.generate string consists of random characters.
43.Atomic Pseudo Random
44.Atomic Simple Random
45.Mersenne
46.Mersenne Twister
47.Mersenne Twister Fast
48.Mersenne Twister algorithm
49.Emulates a dice