Java List Partition partition(List a, int lower, int upper)

Here you can find the source of partition(List a, int lower, int upper)

Description

Performs QuickSort partitioning: Rearranges an array in two partitions.

License

Open Source License

Parameter

Parameter Description
T Data type of the array
a Unsorted array
lower Starting index
upper End index

Return

Pivot point of the partitioned array

Declaration

private static <T extends Comparable<T>> int partition(List<T> a, int lower, int upper) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.List;

public class Main {
    /**//from w ww.ja  va2s .  c  o  m
     * Performs QuickSort partitioning: Rearranges an array in two partitions.
     * The array is permuted so that the elements of the lower partition are
     * always smaller than those of the upper partition.
     *
     * @param <T>   Data type of the array
     * @param a     Unsorted array
     * @param lower Starting index
     * @param upper End index
     * @return Pivot point of the partitioned array
     * @see "Cormen et al. (2001): Introduction to Algorithms. 2nd Edition, page
     * 146"
     */
    private static <T extends Comparable<T>> int partition(List<T> a, int lower, int upper) {
        T x = a.get(upper);
        int i = lower - 1;
        for (int j = lower; j < upper; j++) {
            if (a.get(j).compareTo(x) <= 0) {
                i++;
                exchange(a, i, j);
            }
        }
        exchange(a, i + 1, upper);
        return i + 1;
    }

    /**
     * Swaps two elements at indexes {@code i1} and {@code i2} of an
     * array in-place.
     *
     * @param <T> Data type of the array
     * @param a   Array
     * @param i1  First element index
     * @param i2  Second element index
     */
    private static <T> void exchange(List<T> a, int i1, int i2) {
        T tmp = a.get(i2);
        a.set(i2, a.get(i1));
        a.set(i1, tmp);
    }
}

Related

  1. partition(final List items, final int size)
  2. partition(final List list, final int length)
  3. partition(List list, Integer batchSize)
  4. partition(List all, int partitionSize)
  5. partition(List items, int slices)
  6. partition(List list, int num)
  7. partition(List list, int partitionSize)
  8. partition(List list, int size)