Created
May 24, 2022 19:45
-
-
Save gordonturibamwe/7f2f9d17983b86396211bbeb5709156a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def bubble_sort(array) | |
| return [] if array.class != Array || array.empty? | |
| array.each_with_index do |item, index| # loop through the array | |
| return array if array[index + 1].nil? # return array if the next item is nil | |
| if item > array[index + 1] # if current item is greater than next item | |
| array[index] = array[index + 1] # replace current item with next item | |
| array[index + 1] = item # replace next item with current item | |
| return bubble_sort(array) # call the bubble_sort with new array ~ Recursion | |
| end | |
| end | |
| end | |
| p bubble_sort([4,3,78,2,0,2]) # [0,2,2,3,4,78] | |
| p bubble_sort([9, 8, 0, 4, 1, 6, 2, 7]) # [0, 1, 2, 4, 6, 7, 8, 9] | |
| p bubble_sort([]) # [] | |
| p bubble_sort('addff') # [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment