首页 > 解决方案 > 冒泡排序算法和“int”对象不可下标

问题描述

我已经有很长一段时间了,但我无法解决下面第 4 行代码中发生的错误('int' object is not subscriptable)。

我希望将我的计数器变量与数组中的前一个索引进行比较,如果前一个索引处的元素较大,则交换它们。

任何建议,将不胜感激!

def bubble_sort(list_of_numbers):
    for i in range(len(list_of_numbers)): 


       for j in range(1,len(list_of_numbers)- i): 
           if list_of_numbers[j-1] > list_of_numbers[j]:

               temp = list_of_numbers[j-1]
               list_of_numbers[j-1] = list_of_numbers[j]
               list_of_numbers = temp 

   return list_of_numbers

unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))enter code here

标签: pythonsortingbubble-sort

解决方案


在行中:

list_of_numbers = temp 

list_of_numbers您正在为导致错误的变量分配一个整数。
因此,请使用:

def bubble_sort(list_of_numbers):
    for i in range(len(list_of_numbers)): 


       for j in range(1,len(list_of_numbers)- i): 
           if list_of_numbers[j-1] > list_of_numbers[j]:

               temp = list_of_numbers[j-1]
               list_of_numbers[j-1] = list_of_numbers[j]
               list_of_numbers[j] = temp 

    return list_of_numbers

unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))

或更好的变量交换:

def bubble_sort(list_of_numbers):
    for i in range(len(list_of_numbers)): 


       for j in range(1,len(list_of_numbers)- i): 
           if list_of_numbers[j-1] > list_of_numbers[j]:

               list_of_numbers[j],list_of_numbers[j-1] = list_of_numbers[j-1],list_of_numbers[j]

    return list_of_numbers

unsorted_list = [20, 31, 5, 1, 591, 1351, 693]
print(unsorted_list)
print(bubble_sort(unsorted_list))

推荐阅读