Sorting algortithm with index in java
Clash Royale CLAN TAG#URR8PPP
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;
google it or follow geeksforgeeks.org/arrays-sort-in-java-with-examples
– Ravibhushan Kumar
Aug 8 at 7:48
did I get it right? The problem is to sort the array in ascending order (desired result for above
[10, 24, 53, 95]
) but you want the output with the original indexes (before sorting)?– Carlos Heuberger
Aug 8 at 7:50
[10, 24, 53, 95]
Yeah that's correct
– Priya
Aug 8 at 8:08
I appreciate the quick accept! And welcome to upvote levels ;-)
– GhostCat
Aug 8 at 8:23
6 Answers
6
As this is probably homework, just some ideas:
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.
Pair<Integer, Integer>
Another way to do it would be to convert the array into an array of pairs, e.g.
[95, 0, 53, 1, 24, 2, 10, 3]
and sort that ...– Stephen C
Aug 8 at 7:50
[95, 0, 53, 1, 24, 2, 10, 3]
third option: have a new array with the original indexes that get changed in parallel with the value array (but Stephen's solution is better, less risk of messing it up)
– Carlos Heuberger
Aug 8 at 7:52
@StephenC Good point. Added that idea to my answer.
– GhostCat
Aug 8 at 7:52
@CarlosHeuberger That is just a variation of Stephens idea. Basically you do the mapping in code. I prefer a distinct class instead, too.
– GhostCat
Aug 8 at 7:53
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:
Item
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):
ArrayList
Items
Item
Comparable
Collections.sort
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);
Try this:
Pair
class Pair
int val;
int index;
class Pair
int val;
int index;
sort it by valuez
valuez
index
will keep the initial index
index
This data structure already exists, there is no need to recreate it. See here.
– T A
Aug 8 at 7:55
If I understand the question correctly, only the array exists. But during sorting, values are moved, that's why I suggest creating an additional structure to keep indexes. Correct me if I'm wrong.
– dehasi
Aug 8 at 8:02
The "Pair" data structure is already shipped and can be imported with javafx. Why redo existing classes?
– T A
Aug 8 at 8:21
@TA Thank you for mentioning it. I didn't know that javaFx has such class.
– dehasi
Aug 8 at 8:39
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. Is this also correct way of doing? I am new to Java. I am at a very basic stage.
Where does 'list' come from?
– T A
Aug 8 at 7:57
Oh Sorry. I haven't explained it. I have a list which I converted into array of double datatype. So that is from where the array is generated.
– Priya
Aug 8 at 8:07
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);
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What is your output supposed to be? Do you just want to print to the console? If yes, why not just print the content together with the index in a for-loop?
– T A
Aug 8 at 7:44