0

I am wondering how I can change the output of insertion sort into non-increasing order? For example 537 would be 753. Also, would the runtime would be the same compared to increasing (both best and worst case)?

Pseudo Code:

 INSERTION-SORT(A)
    for j = 2 to A.length
        key = A[j]
        // Insert A[j] into the sorted sequence A[1..j]
        i = j - 1
        while i > 0 and A[i] > key
            A[i +1] = A[i]
            i = i - 1
        A[i + 1] = key
user3393266
  • 59
  • 2
  • 9
  • What do you mean that 537 would be 753? Do you mean that you want to rearrange the digits in each number to be in decreasing order and then sort them? – Kevin Mar 30 '16 at 21:41

1 Answers1

3

Runtime will be unaffected by the change. It would be better to say descending instead of non-increasing when talking about numbers in computer science. Increasing would be ascending. That being said, see the code below for the change you are seeking (pay particular attention to the while loop).

for j = 2 to A.length
    key = A[j]
    i = j - 1
    while i > 0 and A[i] < key
        A[i + 1] = A[i]
        i = i - 1
    A[i + 1] = key
Carlo
  • 188
  • 2
  • 12
  • 4
    It is quite common to speak of "non-increasing" or "non-decreasing". In fact, "descending" does not mean the same thing as "non-increasing" as "descending" does not allow duplicate elements. I don't know where you got the idea that these terms were not used "in computer science." – beaker Mar 31 '16 at 16:50
  • If the OP did mean "descending order", then the only difference in pseudo-code is literally the second comparison arrow reversed in the `while` loop – zenoh Aug 03 '22 at 21:43