假设我的输入是10,8,6,15,2,-1
输出应为15,10,8,15,6,2
我写了一组代码:
public static void main(String[] args) {
int[] unsortesArray=new int[]{10,8,6,15,2,-1};
int len=unsortesArray.length;
for(int i=0;i<len; i++){
for(int j=0; j<len; j++){
if(unsortesArray[i]<unsortesArray[j]){
unsortesArray[i]=unsortesArray[j];
}
}
System.out.println(unsortesArray[i]);
}
}但是没有得到预期的输出。请建议解决方案。
发布于 2018-07-05 01:04:58
您需要交换这两个数字:
public static void main(String[] args) {
int[] unsortesArray=new int[]{10,8,6,15,2,-1};
int len=unsortesArray.length;
for(int i=0;i<len; i++){
for(int j=i+1; j<len; j++){
if(unsortesArray[i]<unsortesArray[j]){
int temp = unsortesArray[i]; // create a temp var to store the value you are going to swap
unsortesArray[i]=unsortesArray[j]; // swap the value
unsortesArray[j] = temp; // save it back again in the array
}
}
System.out.println(unsortesArray[i]);
}
}https://stackoverflow.com/questions/51177710
复制相似问题