这个问题在这里已有答案:
此数组对Ascending中的数字进行排序并打印输出。我想把它改成下降,但我无法弄清楚..我试着改变+到 - 但它似乎没有用..有人可以告诉我如何做到这一点?
public class ArraysSorting {
public static void main(String[] args) {
int [] scores = { 5,8,2,9,3};
sortArrayDesc (scores, scores.length);
}
public static void sortArrayDesc( int [] list, int listLength) {
int index;
int smallestIndex;
int minIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
smallestIndex = index;
for (minIndex = index + 1;
minIndex < listLength; minIndex++)
if (list[minIndex] < list[smallestIndex])
smallestIndex = minIndex;
temp = list[smallestIndex];
list[smallestIndex] = list[index];
list[index] = temp;
}
//display data after sorting
System.out.print("sorted array");
for (index=0; index<listLength; index++) {
System.out.print(list[index] + ",");
}
}
}
我建议你查看关于“冒泡排序”的文章,这与你在这里做的非常接近。然后,继续学习其他排序算法的工作原理。您通常不希望使用n平方排序算法。
要以相反的顺序进行排序,您可能希望使用smallestIndex
变量来存储最大的索引。更改那里的名称,并使用>
行上的if (list[minIndex] < list[smallestIndex])
运算符来查找最大数字。然后,您将在第一个列表位置存储最大数字,在最后一个列表位置存储最小数字。
更新的循环看起来像:
for (index = 0; index < listLength - 1; index++)
{
biggestIndex = index;
for (minIndex = index + 1; minIndex < listLength; minIndex++)
if (list[minIndex] > list[biggestIndex])
biggestIndex = minIndex;
temp = list[biggestIndex];
list[biggestIndex] = list[index];
list[index] = temp;
}
修改此代码以按降序排序数组的一种简单方法是将比较运算符从小于(<)更改为大于(>)。
你的代码:
if (list[minIndex] < list[smallestIndex])
改成:
if (list[minIndex] > list[smallestIndex])
您还应该更改变量命名,否则它没有意义。
听起来你想要一个“for循环”反向运行:
for (i = listLength; i>0; i--) {
System.out.print(list[i] + ",");
}
你需要先开始
list[listLength]
然后递减直到你到达列表/数组的开头
list[0].
我刚做了一些修改。更改了变量名称和重要部分
if(list [maxIndex]> list [largestIndex])//将less小于sign更改为大于
public class ArraysSorting {
public static void main(String[] args) {
int [] scores = { 5,8,2,9,3};
sortArrayDesc (scores, scores.length);
}
public static void sortArrayDesc( int [] list, int listLength) {
int index;
int largestIndex;
int maxIndex;
int temp;
for (index = 0; index < listLength - 1; index++) {
largestIndex = index;
for (maxIndex = index + 1;
maxIndex < listLength; maxIndex++)
if (list[maxIndex] > list[largestIndex])
largestIndex = maxIndex;
temp = list[largestIndex];
list[largestIndex] = list[index];
list[index] = temp;
}
//display data after sorting
System.out.print("sorted array");
for (index=0; index<listLength; index++) {
System.out.print(list[index] + ",");
}
}
}