Here you can find the source of quicksort(final double[] array, final int[] index)
Parameter | Description |
---|---|
array | the array to be sorted |
index | indices of the sorted elements in the original array |
public final static void quicksort(final double[] array, final int[] index)
//package com.java2s; //License from project: Open Source License public class Main { /**//from ww w . j a v a 2 s. co m * Sort an array and store the indices of the sorted elements. * Preconditions : index must be allocated, with the same length as array. * @param array the array to be sorted * @param index indices of the sorted elements in the original array */ public final static void quicksort(final double[] array, final int[] index) { assert array != null; assert index != null; assert array.length == index.length; for (int i = 0; i < index.length; i++) { index[i] = i; } quicksort(array, index, 0, index.length - 1); } private final static void quicksort(final double[] a, final int[] index, int left, int right) { assert a != null; assert index != null; if (right <= left) return; int i = partition(a, index, left, right); quicksort(a, index, left, i - 1); quicksort(a, index, i + 1, right); } private final static int partition(final double[] a, final int[] index, int left, int right) { assert a != null; assert index != null; assert left < right; int i = left - 1; int j = right; while (true) { while (less(a[++i], a[right])) // find item on left to swap continue; // a[right] acts as sentinel while (less(a[right], a[--j])) // find item on right to swap if (j == left) break; // don't go out-of-bounds if (i >= j) break; // check if pointers cross exch(a, index, i, j); // swap two elements into place } exch(a, index, i, right); // swap with partition element return i; } private final static boolean less(double x, double y) { return x < y; } private final static void exch(double[] a, int[] index, int i, int j) { assert a != null; assert index != null; double swap = a[i]; a[i] = a[j]; a[j] = swap; int b = index[i]; index[i] = index[j]; index[j] = b; } }