【发布时间】: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