[英]how to i change this insertion sort from ascending to descending - java
how can i change this insertion sort, from ascending to descending? 如何更改此插入排序,从升序到降序? This is for java.
这是为了java。
for(int top=1;top<dValues.length;top++){
double item=dValues[top];//
int i=top;
while(i>0&&item<dValues[i-1]){
dValues[i]=dValues[i-1];
i--;
}
dValues[i]=item;
}
Just switch the comparisonn operator from <
to >
, so that the bigger (not the smaller) element is inserted first. 只需将comparen运算符从
<
to >
切换,以便首先插入较大的(不是较小的)元素。 It's as simple as that. 就这么简单。
Change this: 改变这个:
while(i > 0 && item < dValues[i-1]) {
To this: 对此:
while(i > 0 && item > dValues[i-1]) {
Right now, you're swapping when the value is less than. 现在,当值小于时,你正在交换。 After the change, you're swapping when values are greater than, thus resulting in a descending list.
更改后,您将在值大于时进行交换,从而生成降序列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.