gpt4 book ai didi

java - 我有一个数组程序,其中的条件是必须返回一个新数组,该数组替换数组中的下一个最高元素

转载 作者:行者123 更新时间:2023-12-02 11:03:12 25 4
gpt4 key购买 nike

假设我有一个输入 [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]);
}
}

但没有得到预期的输出。请提出解决方案。

最佳答案

您需要交换两个数字:

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]);
}
}

关于java - 我有一个数组程序,其中的条件是必须返回一个新数组,该数组替换数组中的下一个最高元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51177710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com