【问题标题】:Bubble sort with 2 different arrays具有2个不同数组的冒泡排序
【发布时间】:2016-11-13 19:15:27
【问题描述】:

string[] z = { "arc", "banana", "cucumber", "deer", "elephant", "fiesta", "giga", "home", "idea", "jump" };
int[] y = { 189, 178, 65, 63, 200, 1000, 10, 15, 28, 20 };

我做了一个由y 排序的z 冒泡排序:

for (int i=0;i<=(y.length-2);i++){
                for (int j=(y.length-1); i<j;j--){
                    if (y[j]<y[j-1]){
                        int temp= y[j-1];
                        y[j-1]=y[j];
                        y[j]=temp;
                        String tempo=z[j-1];
                        z[j-1]=z[j];
                        tempo=z[j];
                    }
                }
            } 
 for (int i=y.length-1;i>0;i--){
 System.out.println(z[i]);}

打印后z 的输出为:

跳,跳,跳,主意,主意,主意,主意,家,家,家

为什么排序会删除z的一些值?

【问题讨论】:

    标签: java sorting bubble-sort


    【解决方案1】:

    您没有使用字符串数组的临时变量。使用您的代码将z[j-1] 的内容保存在tempo 中,但您不会将其写回数组:

    代替

    String tempo=z[j-1];
    z[j-1]=z[j];
    tempo=z[j];
    

    试试这个:

    String tempo = z[j - 1];
    z[j - 1] = z[j];
    z[j] = tempo;
    

    在你的输出循环中,你有一个off by one error。使用&gt;=0

    for (int i=y.length-1;i>=0;i--)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2013-09-28
      • 2021-08-16
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多