Pregunta

how can i change this insertion sort, from ascending to descending? This is for 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;
}
¿Fue útil?

Solución

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.

Otros consejos

Just switch the comparisonn operator from < to >, so that the bigger (not the smaller) element is inserted first. It's as simple as that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top