-2
def INSERTION_SORT(A):
    for j in range(len(A)-1):
        key = A[j]
        i = j+1
        print("***********")
        print(j >= 0)
        print(key > A[i])
        print(j >= 0 & key > A[i])

A = [5,2,4,6,1,3]

INSERTION_SORT(A)

operation result:

***********
True
True
False
***********
True
False
False
***********
True
False
False
***********
True
True
False
***********
True
False
False
[Finished in 52ms]

why are all true, the result is false

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • 1
    That `&` looks suspicious. – Passerby Jan 10 '22 at 13:32
  • Only for `j >= 0` are "all true", and that's because for `for j in range(len(A)-1)`, all `j >= 0`. What exactly is your question? – tobias_k Jan 10 '22 at 13:34
  • `&` is a bitwise operator, maybe you meant `and`? – 3dSpatialUser Jan 10 '22 at 13:34
  • What is meant by "why are all true, the result is false"? There isn't a result anywhere in this code. It's not clear to me what it's supposed to do, seeing how ``INSERTION_SORT`` doesn't insert anything. – MisterMiyagi Jan 10 '22 at 13:35
  • Did you intend to ``print((j >= 0) & (key > A[i]))``? – MisterMiyagi Jan 10 '22 at 13:36
  • 2
    In particular, note that `j >= 0 & key > A[i]` is _not_ `(j >= 0) & (key > A[i])` but `j >= (0 & key) > A[i]`, i.e. `j >= 0 > A[i]`. First comparison is true, second comparison is false for all values, hence the entire chained comparison is false. – tobias_k Jan 10 '22 at 13:36
  • Use the keyword `and`, not `&` because `&` is a bit operator. In Python `and` and `or` are used for boolean comparisons. It should be like this `print(j >= 0 and key > A[i])` – timmyx Jan 10 '22 at 13:46
  • Please don't invalidate existing answers via edits. The new question state makes the answers fail to even address the question. – MisterMiyagi Jan 10 '22 at 14:09

2 Answers2

0

You should use and keyword instead of &

  • and: this is the logical and
  • &: this is the bitwise operator
Paul Kocian
  • 487
  • 4
  • 20
0

You are using the bitwise operator &, in the line print(j >= 0 & key > A[i]). Instead you can use and logical and operator. By the way, your code is not yet doing any sorting operation.

Anand Sowmithiran
  • 2,591
  • 2
  • 10
  • 22