Yoona
Yoona

Reputation: 13

ShellSort in descending order

So my program currently shellSorts in ascending order but I am required to sort in descending order. I would like some help as to what I should change so that it sorts in descending order. Note that built in sort functions are not allowed eg sorted(array, reverse=True)

def shellSort(array):
    n = len(array) 
    gap = n // 2
    while gap > 0: 
        for i in range(gap, n): 
            temp = array[i] 
            j = i 
            while  j >= gap and array[j - gap] < temp: 
                array[j] = array[j - gap]
                j -= gap  
            array[j] = temp 
        gap //= 2

array = []

while True:
    try:
        user_input = input().split()
        array.append(user_input)
    except EOFError:
        break

for i in array:
    shellSort(i)
    print(' '.join(i))

Upvotes: 1

Views: 1747

Answers (1)

blhsing
blhsing

Reputation: 106946

Change:

while  j >= gap and array[j - gap] > temp:

to:

while  j >= gap and array[j - gap] < temp:

so that:

array = [2, 5, 4, 8, 1]
shellSort(array)
print(array)

would output:

[8, 5, 4, 2, 1]

Upvotes: 1

Related Questions