Java Array Sort sortIndices(float[] main)

Here you can find the source of sortIndices(float[] main)

Description

Sort an array in ascending order, but return the index of each sorted element in the original array

License

Open Source License

Parameter

Parameter Description
main an array to sort in ascending order

Return

the index of each sorted element in main

Declaration

public static int[] sortIndices(float[] main) 

Method Source Code

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

public class Main {
    /**/*www  .  ja v a 2s  .c o m*/
     * Sort an array in ascending order, but return
     * the index of each sorted element in the original array
     * @param main an array to sort in ascending order
     * @return the index of each sorted element in main
     */
    public static int[] sortIndices(float[] main) {
        int[] index = new int[main.length];
        for (int i = 0; i < index.length; i++) {
            index[i] = i;
        }

        quicksort(main, index, 0, index.length - 1);

        return index;
    }

    private static void quicksort(float[] a, int[] index, int left, int right) {
        if (right <= left) {
            return;
        }

        int i = partition(a, index, left, right);
        quicksort(a, index, left, i - 1);
        quicksort(a, index, i + 1, right);
    }

    private static int partition(float[] a, int[] index, int left, int right) {
        int i = left - 1;
        int j = right;
        while (true) {
            // find item on left to swap
            while (a[index[++i]] < a[index[right]])
                ; // a[right] acts as sentinel
            // find item on right to swap
            while (a[index[right]] < a[index[--j]]) {
                // don't go out-of-bounds
                if (j == left) {
                    break;
                }
            }

            // check if pointers cross
            if (i >= j) {
                break;
            }

            swap(a, index, i, j); // swap two elements into place
        }

        swap(a, index, i, right); // swap with partition element
        return i;
    }

    private static void swap(float[] a, int[] index, int i, int j) {
        int tmp = index[i];
        index[i] = index[j];
        index[j] = tmp;
    }
}

Related

  1. sortIndex(double[] A)
  2. sortIndex(double[] doubleArray)
  3. sortIndexes(final T[] array)
  4. sortIndexesDescending(final double[] in)
  5. sortindices(double[] x)
  6. sortInPlace(final double[] v, final int i, final int j)
  7. sortInPlace(int[] array)
  8. sortInterval(byte[] x, int start, int end)
  9. sortKeyValuePairs(long[] keys, double[] values, int startInd, int endInd)