0

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

3
  • 1
    Could you specify the language in your tags please? Looks like C, but want to be sure... Also, the various functions you are using look to be from a library - perhaps the Processing library? Commented Oct 15, 2015 at 23:19
  • Hi @MichaelDorgan I am using processing which is based on Java Commented Oct 15, 2015 at 23:27
  • Why are you using two arrays? Maps would be a much better choice Commented Oct 16, 2015 at 0:47

1 Answer 1

1

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot @v.k. the code works well. I now have to start learn about the maps :)
There is also intDict which you can try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.