user1496259
user1496259

Reputation: 41

Sorting with Index Retention

Instead of Bubble Sort which Sorting technique can be used to sort an array of integers such that at the time of output i can display its position in original array??

INPUT 4 5 3 6 1

OUTPUT

   INDEX : VALUE
     5   :   1
     3   :   3
     1   :   4
     2   :   5
     4   :   6

Upvotes: 2

Views: 98

Answers (2)

assylias
assylias

Reputation: 328598

You can use a TreeMap where the key is the value in the array and the value is the index + 1. It will do what you need automatically.

Sample code:

public static void main(String[] args) throws ParseException {
    int[] array = new int[] {4, 5, 3, 6, 1};
    Map<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>();

    for (int i = 0; i < array.length; i++) {
       sortedMap.put(array[i], i + 1);
    }
    System.out.println(sortedMap);
}

outputs:

{1=5, 3=3, 4=1, 5=2, 6=4}

Note: this only works if you don't have duplicates in the original list

Upvotes: 5

Marko Topolnik
Marko Topolnik

Reputation: 200148

Solution with a holder object:

public class IntWithIndex implements Comparable<IntWithIndex>
{
  public final Integer value;
  public final int index;

  public IntWithIndex(int value, int index) { 
    this.value = value; 
    this.index = index; 
  }

  public int compareTo(IntWithIndex other) { 
    return this.value.compareTo(other.value); 
  }
  public String toString() { 
    return String.format("[%d,%d]", value, index); 
  }

  public static void main(String[] args) {
    final IntWithIndex[] ts = new IntWithIndex[5];
    int i = 0;
    for (int x : new int[] { 4, 5, 3, 6, 1 }) 
      ts[i] = new IntWithIndex(x, i++);
    Arrays.sort(ts);
    System.out.println(Arrays.toString(ts));
  }
}

Upvotes: 1

Related Questions