inverse java Sort shell

Asked

Viewed 162 times

0

personal I’m having a doubt, how to make descending reverse Sort shell.

private static void shellsort(int v[], int n) {
    int i, j, aux, h = 1;
    do
        h = 3 * h + 1;
    while (h < n);
    do {
        h /= 3;
        for (i = h; i < n; i++) {
            aux = v[i];
            j = i - h;
            while (j >= 0 && aux < v[j]) {
                v[j + h] = v[j];
                j -= h;
            }
            v[j + h] = aux;
        }
    } while (h > 1);
}
  • Hey, what’s wrong with the example you have there ?

  • in the example it does in ascending order, and I would like in descending order =( Vector[995]= 99486 Vector[996]= 99492 Vector[997]= 99583 Vector[998]= 99701 Vector[999]= 99765

  • To change from increasing to decreasing simply change the condition aux < v[j] for aux > v[j]

1 answer

1

Good evening, to change from crescent to descending in your code, just change the condition aux < v[j] for aux > v[j]

for example:

private static void shellsort(int v[], int n, boolean crescente) {
    int i, j, aux, h = 1;
    do
        h = 3 * h + 1;
    while (h < n);
    do {
        h /= 3;
        for (i = h; i < n; i++) {
            aux = v[i];
            j = i - h;
            if (crescente) {
                while (j >= 0 && aux < v[j]) {
                    v[j + h] = v[j];
                    j -= h;
                }
            } else {
                while (j >= 0 && aux > v[j]) {
                    v[j + h] = v[j];
                    j -= h;
                }
            }
            v[j + h] = aux;
        }
    } while (h > 1);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.