Reputation: 21
I have two arrays where one array represents a collection of names and the other describes their associated marks.I wanted to sort the marks inside the array in ascending order, and then also the respective names related to the marks.
My aim is to create a rank list. I am using Processing to do this
float sum = 0;
String [] name = {"A", "B", "C", "D","E"};
float [] mark = {12, 2, 4, 6, 23};
void setup() {
size(600, 600);
smooth();
}
void draw() {
background(225);
fill(0);
println(name.length);
for (int i =0; i<name.length; i++) {
text(name[i] + ":"+ mark[i], 100, 100+i*50);
}
}
/////// i wanted to sort it as E:23, A:12, D:6, C:4, B:2
It would be great if someone can help me with this. :)
Many thanks in advance, Yousuf
Upvotes: 0
Views: 2461
Reputation: 2854
You can make a data holder class implementing Comparable
. I think you could also use a Map, like a hashMap.
Here a data holder class example:
import java.util.Collections;
ArrayList <Data> d = new ArrayList<Data>();
void setup() {
size(600, 600);
d.add(new Data("A", 12));
d.add(new Data("B", 2));
d.add(new Data("C", 4));
d.add(new Data("D", 6));
d.add(new Data("E", 23));
println("before sorting:\n" + d);
//used reverseOrder as it goes decrescent, but you could just reverse
//the "natural" order in the class it self. Exchange -1 and 1 in compareTo()
// and use Collections.sort(d); here
Collections.sort(d, Collections.reverseOrder());
println("after sorting:\n" + d);
}
/////// i wanted to sort it as E:23, A:12, D:6, C:4, B:2
class Data implements Comparable {
String name;
int mark;
Data(String _n, int _m) {
name = _n;
mark = _m;
}
// this sets the 'natural' order of Data
@Override
int compareTo(Object o) {
Data other = (Data) o;
if (other.mark > mark) {
return -1;
} else if (other.mark < mark) {
return 1;
}
return 0;
}
// this to get a nice looking output in console...
@Override
String toString() {
return name + ":" + nf(mark, 2);
}
}
Upvotes: 1