简体   繁体   English

通过对数组进行排序来创建排名列表

[英]creating a rank list by sorting an array

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 在此先感谢您,优素福

You can make a data holder class implementing Comparable . 您可以使数据持有人类实现Comparable I think you could also use a Map, like a hashMap. 我认为您也可以使用Map,例如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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM