【问题标题】:Do same thing as sort(arrayList) without an array??? In PROCESSING与没有数组的 sort(arrayList) 做同样的事情???进行中
【发布时间】:2012-10-02 03:00:04
【问题描述】:

有没有办法对不在数组中的整数进行排序?

我知道您可以将sort(arrayList) 类型的想法与数组一起使用,但示例...

如果我有单独的变量,可以完成类似的任务吗?例如,如果我有三个数字,我可以对它们进行排序,以便它们从大到小打印吗?

谢谢!

【问题讨论】:

  • 不确定您想要达到的目标。在 Java 中,如果您有 n 个变量 a1、a2、a3...aN,您始终可以为其创建一个数组/数组列表。 int myArray[] = {a1,a2....,aN};然后调用 Arrays.sort(myArray) 如果您只有 3 个数字,您可以编写一个简单的 if else 块来查找最大、最小和中间数字。
  • 我能想到一个 O(n^2) 算法。找到最大数量打印它,并标记它已被处理。找到下一个最大的未标记数字并打印出来,依此类推。

标签: sorting processing


【解决方案1】:

如果你的 ArrayList 包含对象,这些对象的类型可以实现Comparable,所以你可以使用Collections'排序方法。如果您愿意,您可以将 ArrayList 转换为数组并以这种方式对其进行排序,但它看起来不像您想要的那样。下面是一个使用这两种方法的简单示例:

void setup(){
  int count = 100,now;
  stroke(192,0,0);strokeWeight(count/width);
  //make up some data
  ArrayList<Pair> p = new ArrayList<Pair>();
  for(int i = 0 ; i < count ; i++) {
    Pair pair = new Pair(i,random(10,100));
    p.add(pair);
    float x = map(i,0,count,i,width);
    float y = map(pair.distance,10,100,0,50);
    line(x,50,x,50-y);
  }

  now = millis();

  //Sort typed ArrayList by converting to array first
  println("sort typed array: \n");
  Pair[] s = new Pair[p.size()];
  p.toArray(s);
  Arrays.sort(s);

  println("took " + (millis()-now) + " ms");

  now = millis();

  //Sort using Collections
  println("\n\nsorting typed array list: \n" );
  Collections.sort(p);

  println("took " + (millis()-now) + " ms");

  stroke(0,192,0);
  for(int i = 0 ; i < count ; i++) {
    Pair pair = p.get(i);
    float x = map(i,0,count,i,width);
    float y = map(pair.distance,10,100,0,50);
    line(x,100,x,100-y);
  }

}
class Pair implements Comparable<Pair>{
  public int id;
  public float distance;
  Pair(int i, float d){
    id = i;
    distance = d;
  }
  int compareTo(Pair p){
    if     (p.distance > this.distance) return  1;
    else if(p.distance < this.distance) return -1;
    else return 0;
  }
  String toString(){    return id+":"+distance;    }
}

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 2019-07-12
    • 2020-09-28
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    相关资源
    最近更新 更多