Алгоритм сортировки вставки выключен одной ошибкой - PullRequest
1 голос
/ 07 марта 2019

Мой код Python для алгоритма вставки сортировки почти работает, но по какой-то причине первый элемент моего списка не отсортирован - может кто-нибудь сказать мне, где проблема?

listToBeSorted = [7,2,4,3,6,5,1]
for pointer in range(1, len(listToBeSorted )):
    itemToBeInserted = listToBeSorted[pointer]
    currentIndex = pointer - 1
    while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > 0:
       listToBeSorted[currentIndex + 1] = listToBeSorted[currentIndex]
       currentIndex -= 1
    listToBeSorted[currentIndex + 1] = itemToBeInserted

print(listToBeSorted)

Ответы [ 2 ]

1 голос
/ 07 марта 2019

Проблема в этом утверждении

while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > 0

, которое должно быть

while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > -1

Если currentIndex всегда больше 0, то первый элемент списка никогда не сортируется, потому чтони один элемент в списке не будет вставлен в начало списка.

listToBeSorted = [7,2,4,3,6,5,1]
for pointer in range(1, len(listToBeSorted )):
    itemToBeInserted = listToBeSorted[pointer]
    currentIndex = pointer - 1
    while listToBeSorted[currentIndex] > itemToBeInserted and currentIndex > -1:
       listToBeSorted[currentIndex + 1] = listToBeSorted[currentIndex]
       currentIndex -= 1
    listToBeSorted[currentIndex + 1] = itemToBeInserted

print(listToBeSorted)
1 голос
/ 07 марта 2019

Ваш код завершает цикл while слишком рано. Вместо currentIndex > 0 требуется currentIndex >= 0, чтобы при необходимости можно было сместить первое значение в списке вперед.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...