Java Array Sort sortWith(final int[] ary, int[] ary2)

Here you can find the source of sortWith(final int[] ary, int[] ary2)

Description

Sort two arrays - the second one is sorted according the first one.

License

Apache License

Declaration

public static void sortWith(final int[] ary, int[] ary2) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.*;

public class Main {
    /** Sort two arrays - the second one is sorted according the first one. */
    public static void sortWith(final int[] ary, int[] ary2) {
        Integer[] sortOrder = new Integer[ary.length];
        for (int i = 0; i < sortOrder.length; i++)
            sortOrder[i] = i;//  ww  w  . ja  va 2  s.co m
        Arrays.sort(sortOrder, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return ary[o1] - ary[o2];
            }
        });
        sortAccording2(ary, sortOrder);
        sortAccording2(ary2, sortOrder);
    }

    /** Sort given array according given sort order. Sort is implemented in-place. */
    public static void sortAccording2(int[] ary, Integer[] sortOrder) {
        Integer[] so = sortOrder.clone(); // we are modifying sortOrder to preserve exchanges
        for (int i = 0; i < ary.length; i++) {
            int tmp = ary[i];
            int idx = so[i];
            ary[i] = ary[idx];
            ary[idx] = tmp;
            for (int j = i; j < so.length; j++)
                if (so[j] == i) {
                    so[j] = idx;
                    break;
                }
        }
    }

    /** Sort given array according given sort order. Sort is implemented in-place. */
    public static void sortAccording2(boolean[] ary, Integer[] sortOrder) {
        Integer[] so = sortOrder.clone(); // we are modifying sortOrder to preserve exchanges
        for (int i = 0; i < ary.length; i++) {
            boolean tmp = ary[i];
            int idx = so[i];
            ary[i] = ary[idx];
            ary[idx] = tmp;
            for (int j = i; j < so.length; j++)
                if (so[j] == i) {
                    so[j] = idx;
                    break;
                }
        }
    }
}

Related

  1. sortStrings(String[] strings)
  2. sortSubFiles(String[] p_subFiles)
  3. sortTable(String[][] data, int index)
  4. sortToFXYSumOrder(final double[] coeffs)
  5. sortTwoArrays(A[] firstArray, B[] secondArray)
  6. SortWithIndex(double[] arr, Integer[] i)
  7. sortWithInds(int[] x, int[] idx)
  8. sortWithNoMissingValues( double[] array)
  9. toSortedArray(Collection collection)