Skip to content

Instantly share code, notes, and snippets.

@Josephchinedu
Created April 12, 2022 22:06
Show Gist options
  • Save Josephchinedu/925b190c1b6e7067421ddffa5b3ad413 to your computer and use it in GitHub Desktop.
Save Josephchinedu/925b190c1b6e7067421ddffa5b3ad413 to your computer and use it in GitHub Desktop.
sorting algorithm
## bubble sort is the most basic sorting algorithm and it works by repeatedly
## swapping adjcent elements if they're not ordered then it order it
## bubble sort algorithm takes unsorted lisr in pairs and compare each element and swap the highest to the right
## if they are not ordered.
## example:
## def bubbleFunc(data):
## ## this function takes unsorted list
## ## create a variable that that stores the length of item that's going to be use for indexing.
## item_length = len(data) - 1
## ## reason why we're substracting 1 from the length is becasue we don't need to compare the last element in the "data" list
## ## because thet're no element after the last element. so we don't need to check the last element
## sorted = False
## ## we create a boolean field value that will determine the condition of our while loop
## while not sorted:
## sorted = True
## ## we're re-assigning "True" to "sorted" boolean variable whenever the loops runs.
## ## a for loop that will go from the range of 0 to the length os list "data"
## for i in range(0, item_length):
## ## let's do a comparison.
## ## if the sorted list in the current position of the current loop is greater than the next
## ## item, we flip it
## if data[i] > data[i + 1]:
## sorted = False
## data[i], data[i + 1] = data[i + 1], data[i]
## return data
## print(bubble([1,2,3,4,1,3,8,5]))
def bubbleFunc(data):
item_len = len(data) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, item_len):
if data[i] > data[i + 1]:
sorted = False
data[i], data[i + 1] = data[i + 1], data[i]
return data
print(bubbleFunc([2,1,3,4,1,2,9,2,19]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment