last_thing and use it to initialise your array, which is fine, however you also use it within your actual
bubble_sort function. This seems wrong, it would be better to use the length of the supplied array in order to determine when to stop. This will make your code more portable and able to handle different sized arrays.
When to check for
You only need to check if the array is sorted at the end of each pass. As it stands, you're checking if the array is sorted for each entry you're processing, even if you haven't done anything with the array. Which feels like you're turning an O(n^2) algorithm into an O(n^3) solution. Another approach you can use is to keep track of whether or not you've actually done a swap on a given pass, if you haven't then you know it's because the list is already sorted.
This is probably very subjective, but I don't like this:
To me, it makes the start of each pass through the list less obvious than other methods.
Algorithms are used to solve general problems. There are several instances where you've tied your solution to the exact problem (such as your use of
last_thing) you're solving which means it can't solve the general problem. The way you've implemented
correct_order is another good example of this. You iterate through the list and make sure that each item in the list has the same value as it's position in the list. This works for your exact problem, but makes your algorithm useless if you wanted to sort
[8,2,4,6]. Consider writing unit tests so that you can actually exercise your code with different inputs to make sure they can be handled. This will help you to build code that is not so tightly coupled to the specific problem you're solving.
Odds and Bobs
- You've imported
time, but you're not using it. Redundant code adds unnecessary noise, consider removing the unused import.
- Names matter.
d aren't very descriptive, consider expanding the names to describe what it is they represent.
- If you just need two values (0, 1), consider using a boolean instead (False/True).
- Try to standardise on your spacing, sometimes you have spaces around operators sometimes you don't... it can make the code look messy.
Taking some of the above into account, a refactored version of your code might look something like this:
while not correct_order(array):
for index in range(len(array) - 1):
if array[0+index] > array[1+index]:
array[0+index],array[1+index] = array[1+index],array[0+index]
for i in range(len(array)-1):
if array[i] > array[i+1]: