Often we face a situation where we need to sort an array along with it’s index. Later we can use sorted index on various purpose.The following code is a modified version of Insertion sort which will do the work.
For the input of {10,5,6,4,13,7} it will sort the array in ascending order :{4,5,6,7,10,13} and return the sorted index array which is {3,1,2,5,0,4 }.
public class SortedIndex { //public int[] handDiff=new int[5]; public static double[] mainArray={10,5,6,4,13,7}; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int sorteIndex[] = modifiedInsertionSort(); for(int i=0;i<mainArray.length;i++) { System.out.print(sorteIndex[i]); } } public static int[] modifiedInsertionSort() { double sortedArray[] = new double[mainArray.length]; System.arraycopy(mainArray, 0, sortedArray, 0, mainArray.length); // ----------Modified insertion Sort int i, j; double newValue; int indexKey; int sortedIndex[] = new int[sortedArray.length]; for (i = 0; i < sortedIndex.length; i++) { sortedIndex[i] = i; // pointsIn[i]=i; } for (i = 1; i < sortedArray.length; i++) { newValue = sortedArray[i]; indexKey = sortedIndex[i]; j = i; while (j > 0 && sortedArray[j - 1] > newValue) { sortedArray[j] = sortedArray[j - 1]; sortedIndex[j] = sortedIndex[j - 1]; j--; } sortedIndex[j] = indexKey; sortedArray[j] = newValue; } return sortedIndex; } }