0

我目前正在尝试手动将 Double Array 排序为升序。我遇到的问题是输出仅在顶部列出了第一个最小值(这是正确的),但将其余值列出为 0.0。(值范围从 -5 到 +20)。下面是我在排序时的编码尝试。任何帮助将不胜感激。谢谢你。

             int index; 
             double temp;

             for(index = 0; index < x.length; index++)
               { 
                 for(int j = 0; j < x.length - 1; j++)
                    {
                       if(x[j + 1] < x[j])
                          {
                             temp = x[j + 1];
                             x[j + 1] = x[j];
                             x[j] = temp;  
                           }
                      }
                }
4

3 回答 3

1

你很接近,但你需要将 x[index] 与 x[j] 进行比较:

for (int index = 0; index < x.length - 1; index++) {
  for (int j = index + 1; j < x.length; j++) {
    if (x[j] < x[index]) {
      temp = x[j];
      x[j] = x[index];
      x[index] = temp;
    }
  }
}
于 2013-07-15T18:22:05.170 回答
1

这几乎是你到达那里的冒泡排序。尝试这个 :

 public static void sort(int[] x) {
  boolean sorted=true;
  int temp;

  while (sorted){
     sorted = false;
     for (int i=0; i < x.length-1; i++) 
        if (x[i] > x[i+1]) {                      
           temp       = x[i];
           x[i]       = x[i+1];
           x[i+1]     = temp;
           sorted = true;
        }          
  } 

}

但科林是对的。你最好使用 Arrays.sort。

于 2013-07-15T18:09:36.780 回答
1

您可以使用Arrays.sort(x)from the java.utilpackage 对数组进行排序。

于 2013-07-15T18:11:15.333 回答