Priya
Priya

Reputation: 339

Sorting algortithm with index in java

I have a set of values for srting algorithm. I have successfully sorted them out. But I also want to have the index for each element after sorting. For example like :

Array = [95, 53, 24, 10]
Output after sorting should be like :
10 at index 3, 24 at index 2, 53 at index 1 and 95 at index 0

I have used the following logic for sorting. But unable to get the indexes

for (int p = 0; p < ((list.size()) - 1); p++) {
    int min = p;                 
    count++;

    for(int q=p+1; q<list.size();q++) {
        if(doubleArray[q] < doubleArray[min]) {
            min = q;
        }
    }

    double smallNumber = doubleArray[p];
    doubleArray[p] = doubleArray[min];
    doubleArray[min] = smallNumber;                  
}

Upvotes: 1

Views: 609

Answers (6)

Priya
Priya

Reputation: 339

I have just tried the following and it worked.

int[] index = {0,1,2,3}
for (int p=0;p<((list.size())-1);p++) 
                 {
                     int min = p;
                     
                     count++;
                     for(int q=p+1; q<list.size();q++) 
                     {
                        if(doubleArray[q]< doubleArray[min])
                        {
                            min = q;
                        }
                     }
                     double smallNumber = doubleArray[p];
                     doubleArray[p] = doubleArray[min];
                     doubleArray[min] = smallNumber;
                     
                     store = index[p];
                     index[p] = index[min];
                     index[min] = store;
                    
                 }
}

and it worked.

Upvotes: 0

Faiz Akram
Faiz Akram

Reputation: 558

Here you find the old index and shorted value

Map<Integer, Integer> map1 = numbers.stream().collect(Collectors.toMap(i -> i, i -> numbers.indexOf(i))).           entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));

//output {10=3, 24=2, 53=1, 95=0}

Upvotes: 0

Niels Billen
Niels Billen

Reputation: 2199

As previously suggested, I would also recommend using an additional Item class which stores the item on which you want to sort and the initial index:

public class Item<T extends Comparable<T>> implements Comparable<Item<T>> {
    public final T item;
    public final int index;

    public Item(T item, int index) {
        if (item == null)
            throw new NullPointerException("the given item is null!");
        this.item = item;
        this.index = index;
    }

    @Override
    public int compareTo(Item<T> t) {
        if (t == null)
            return 1;
        return item.compareTo(t.item);
    }
}

When you need to sort the array of doubles, you first create an ArrayList containing the Items which store the doubles of the input array and the initial index. Since the Item class implements the Comparable interface, you can use Collections.sort for sorting (which will be faster than your bubblesort implementation):

public static void sort(Integer... array) {
    List<Item<Integer>> copy = new ArrayList<Item<Integer>>(array.length);

    // copy the input array
    for (int i = 0; i < array.length; ++i)
        copy.add(new Item<Integer>(array[i], i));


    Collections.sort(copy);

    for (Item<Integer> t : copy)
        System.out.println(t.item + " at index " + t.index);
}

Upvotes: 2

NullPointer
NullPointer

Reputation: 152

I would suggest below approach:

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.SortedSet;
    import java.util.TreeSet;

    public class trial
    {
     public static void main(String[] args)
     {
    List<Integer> aList = Arrays.asList(95, 53, 24, 10);
    Map<Integer, Integer> aMap = new HashMap<>();

    int index = 0;
    for( Integer aInteger : aList )
    {
      aMap.put(aInteger, index);
      index++;
    }

    SortedSet<Integer> keys = new TreeSet<>(aMap.keySet());

    for( Integer key : keys )
    {
      Integer value = aMap.get(key);
      System.out.println(key + " at index " + value);
     }
    }
    }

Upvotes: 0

GhostCat
GhostCat

Reputation: 140427

As this is probably homework, just some ideas:

  • before sorting, create a copy of your initial array
  • after sorting, iterate the original array, and then find the index of each value in the sorted array, and print that
  • the tricky part is dealing with values that show up repeatedly. but that is something that depends on your exact requirements.

Alternatively, you could look into introducing a helpful data structure, such as a Pair<Integer, Integer> class. The first entry represents the value, the second one an index. Then you can define your own "sorting" on that class.

Upvotes: 4

dehasi
dehasi

Reputation: 2773

Try this:

  1. Create a Pair class like

class Pair { int val; int index; }

  1. sort it by valuez

  2. index will keep the initial index

Upvotes: 0

Related Questions