为何我的插入排序(Insertion Sort)代码无法运行?
解决你的插入排序代码运行问题
Hey there! Let's break down why your insertion sort code isn't producing visible results—your core sorting logic is actually solid, you just need to add a few pieces to make it run and show you the output:
- You need a test list: You haven't defined any data to sort yet. Let's create a sample unsorted list to test with.
- You need to call your sorting function: Defining the functions doesn't run them—you have to explicitly invoke
insertionSortwith your list. - You need to print the result: After sorting, you'll want to output the sorted list to see if it worked.
Here's your updated code with these additions:
def insertionSort(lst): k = 1 while k < len(lst): x = lst.pop(k) insertInOrder(lst, k, x) k += 1 def insertInOrder(lst, k, x): while k >= 1 and lst[k-1] > x: k -= 1 lst.insert(k, x) # Step 1: Define an unsorted list unsorted_list = [5, 3, 8, 1, 2, 7] # Step 2: Call the sorting function on the list insertionSort(unsorted_list) # Step 3: Print the sorted result print("Sorted list:", unsorted_list)
When you run this, you'll see the output: Sorted list: [1, 2, 3, 5, 7, 8]
A quick note: Since lists in Python are mutable, your insertionSort function modifies the original list directly—you don't need to return the list from the function to access the sorted version.
内容的提问来源于stack exchange,提问作者FindingJango
相关产品推荐
相关产品推荐

