【问题标题】:Bubble sort not printing last element冒泡排序不打印最后一个元素
【发布时间】:2014-11-14 18:26:54
【问题描述】:

我的代码要求用户输入温度量并打印出平均值,然后按升序和降序对温度进行排序。对于升序,我使用了选择排序,对于降序,我使用了冒泡排序。我的问题是,当我使用冒泡排序时,最后一个排序的元素不会打印,我不确定它为什么会这样做。我究竟做错了什么?

   public static void main(String[] args) {

    Scanner keyboard=new Scanner(System.in);
    System.out.println("How many temperatures?");
    int size=keyboard.nextInt();
    int temp[]=new int[size];
    System.out.println("Please enter "+temp.length+" temperatures");
    double sum=0;
    for(int i=0;i<temp.length;i++){
        temp[i]=keyboard.nextInt();
        sum=sum+temp[i];
    }
    double average=sum/temp.length;
    System.out.println("The average temperature is: "+average);


  System.out.println(" "); 
  System.out.println("Selection sort algorithm for ascending order");
  int min;
  for (int i = 0; i < temp.length; i++) {

    min = i;
    for (int j = i + 1; j < temp.length; j++) {
        if (temp[j] < temp[min]) {
            min = j;
        }
    }
    if (min != i) {
        int temporary_var = temp[i];
        temp[i] = temp[min];
        temp[min] = temporary_var;
    }
    System.out.print(temp[i]+ " ");

}
 System.out.println("");
 System.out.println("Bubble sort algorithm for descending order");   
 for(int i=0; i<temp.length-1; i++)
 {
  if(temp[i]>temp[i+1])  
  {
   int temporary_var = temp[i ];                //swap elements
   temp[i] = temp[ i+1 ];
   temp[i+1] =  temporary_var; 
  }
 System.out.print(temp[i]+" ");    
}
}

}

【问题讨论】:

    标签: sorting


    【解决方案1】:

    您正在排序循环中打印,该循环是 for(int i=0; i&lt;temp.length-1; i++),长度为 1。这就是它不打印最后一个元素的原因。将其更改为 for(int i=0; i&lt;temp.length; i++),因为您已经有一个 &lt; than 运算符。

    【讨论】:

    • 当我使用 for(int i=0; i
    • 而不是 if(temp[i]>temp[i+1]) 使用 if((itemp[i+1])
    • 我会试试这个,因为我有一个索引越界异常
    • 谢谢!这正是我所需要的
    【解决方案2】:

    我不相信您的冒泡排序算法是正确的。只有一个循环和交换?这只是冒泡排序的一次,不会为您对数组进行排序。
    首先更正您的算法,然后在循环外输出数字
    这是冒泡排序的正确代码

        for(int k=0; k<temp.length; k++)
         {
          for(int i=0;i<temp.length-1;i++)
          {
            if(temp[i]>temp[i+1])  
            {
              int temporary_var = temp[i ];                //swap elements
              temp[i] = temp[ i+1 ];
              temp[i+1] =  temporary_var; 
            }  
    
        }
    
    //print array here
    

    【讨论】:

      【解决方案3】:

      冒泡排序的 print 语句是 for 循环的一部分,它只能达到长度为负 2 的索引。在零索引数组上,最后一个索引是长度 - 1。

      【讨论】:

        猜你喜欢
        • 2018-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 2016-12-18
        • 2022-01-26
        • 2012-03-01
        • 2016-04-13
        相关资源
        最近更新 更多