Labels

Arduino (1) Bugs (3) C (1) HTML (1) Install (3) Linux (27) Maths (1) Python (11) Raspberry Pi (4)

Thursday, 19 November 2015

Bubble sort in 5 lines using Python

The bubble sort is used to put the numbers in order from smallest to biggest. The current method is not the most efficient way of sorting the numbers into order as it compares each number to every other number.The amount of iterations it takes can be calculated by n^2 with n being the number of values in the array.
numbers = [9,1,2,3,45,4332,3232,29,-1]
for j in range(len(numbers)):
    for i in range(len(numbers)-1):
        if(numbers[i] > numbers[i+1]):
            numbers[i],numbers[i+1] = numbers[i+1],numbers[i]


First setup the array with numbers not in any order
numbers = [9,1,2,3,45,4332,3232,29,-1]
 


Now create a for loop that loops depending on the amount numbers - 1 as the array index starts at 0.
for j in range(len(numbers)):


Another for loop nested inside the for loop to do the same thing.
for i in range(len(numbers)-1):


Compare the value of the current number with the number that is next in array.
if(numbers[i] > numbers[i+1]):


If this is true then swap them around so that the smaller one is first.
numbers[i],numbers[i+1] = numbers[i+1],numbers[i]



The array before the iteration starts looks like this
[9, 1, 2, 3, 45, 4332, 3232, 29, -1]


After the code runs it is in order like this
[-1, 1, 2, 3, 9, 29, 45, 3232, 4332]