前言:这不适用于家庭作业,但它是针对“编码挑战”,它在我的课程中不值得任何分数,但我希望更全面地了解数组和循环,所以我希望这在我移动之前工作在课程中。
所以这是我的问题。我正在尝试设计一种反向排序数组并将数字从最高位置放到最低位置的方法。我现在的代码是:
public static void selectionReverseSort (int[] array)
{
int startScan, index, maxIndex, maxValue;
for (startScan = 0; startScan < (array.length - 1); startScan++)
{
maxIndex = startScan;
maxValue = array[startScan];
for(index = startScan + 1; index < array.length; index++)
//index is 1
{
if (array[index] > maxValue)
{
maxValue = array[index];
//maxValue now becomes the second array number
maxIndex = index;
//maxIndex becomes the current index number.
}
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
}
}
}
这段代码的问题在于,如果它们以升序开头,它似乎只对数组进行反向排序,否则它只重复前几个数组槽的最高数。有人想帮我理解这里发生了什么以及我能做些什么来解决这个问题?
答案 0 :(得分:1)
您选择的算法似乎是找到数组中的最大值,然后使用交换将最大值移动到数组中的第一个位置。然后你对从第二个元素开始的子数组做同样的事情,然后用从第三个开始的子数组开始,依此类推。
这会有效,但你的代码太早了。在进行交换之前,需要等到内循环完成后找到最大的元素。我没有对它进行过测试,但我认为您需要做的就是移动这两个语句:
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
在内环之外。
答案 1 :(得分:1)
您的算法是正确的。但即使您的数量很少,您也会不必要地进行交换。我更新了你的逻辑。
import java.io.*;
public class Hey{
public static void main(String args[])throws IOException{
int []ar = {1,2,5,4,6,8,7,9,10};
selectionReverseSort(ar);
}
public static void selectionReverseSort (int[] array){
int startScan, index, maxIndex, maxValue;
for (startScan = 0; startScan < (array.length - 1); startScan++){
maxIndex = startScan;
maxValue = array[startScan];
for(index = startScan + 1; index < array.length; index++){
//index is 1
if (array[index] > maxValue){
maxValue = array[index];
//maxValue now becomes the second array number
maxIndex = index;
//maxIndex becomes the current index number.
//swap only if the condition is true
array[maxIndex] = array[startScan];
array[startScan] = maxValue;
}
}
}
}
for(int i = 0; i < array.length; i++ )
System.out.println(array[i]+"");
}
}
我建议您使用除插入排序之外的任何其他更好的排序算法。
答案 2 :(得分:0)
这只是一个使用java API的单行解决方案:
public static void selectionReverseSort (int[] array){
Collections.sort(Arrays.asList(array),Collections.reverseOrder());
}
将其保留以备将来使用:)。