How to make a sorting algorithm step by step
When creating an algorithm like a bubble sort algorithm, the position of data will be random. So in order to create an algorithm that will sort any list of data given with its elements in random positions, we'll need to access the data by the index of the list.
Bubble sort can be split into two loops at the very basic level. Where one loop iterates the phases and the other the replacement/swap of elements.
Yeah, I know, I also couldn't understand what this meant but hang on,
okay so check this out. You have a list of numbers
[2,4,3,5,6,7]
Our minds can easily sort this because we know which number is greater than the other. However the computer doesn't so we'll have to tell it how.
First thing you need to do is go through each element and compare if that element is greater than the one next to it sequentially.
So we'll take 2, compare it with 4 and if it is greater than 4 we'll swap the two numbers. In this case no so we leave it.
in the next case we'll take 4 compare it with 3, if it is greater, we'll swap the two numbers and now our list we'll be like this: [2,3,4,5,6,7]
data = [2,4,3,5,6,7]
for x in range(len(data)-1):
if data[x] > data[x+1]:
num = data[x]
data[x] = data[x+1]
data[x+1] = num
Now this is the main part which I referred to as the replacement/swap loop. in order to perfectly sort our list, we'll need to make a time for each element to be compared to all other elements. So that if we had in any case we had a list like [4,5,8,6,2,9,3] we wouldn't experience any issues.
And this is where the phase loop comes in. This part allows us to compare an element to other elements in its own phase. The number of iterations will be dependent on the length of the list. [1,7,8,5,6,4] will have six phases as len([1,7,8,5,6,4])
= 6
To put it all together now,
data = [1,7,8,5,6,4]
for i in range(len(data)-1):
for x in range(len(data)-1):
if data[x] > data[x+1]:
num = data[x]
data[x] = data[x+1]
data[x+1] = num
print(data)
Test of the code:
Top comments (0)