Bubble Sort
This sorting algorithm works by taking to elements within an array and compares the two. Depending on how it is sorting the elements in an array, will switch the two values around. For example, if we had an array [3, 17, 83, 6, 24, 52] and we want to order those elements, smallest to largest. The first two elements, 3 and 17 won’t be swapped, same applies for 17 and 83. However, with elements 83 and 6, the two will swap as 6 is less than 83. Once the algorithm has sorted through the array the first time, we should end up with [3, 17, 6, 24, 52, 83]. This array hasn't been sorted so the algorithm needs to run again or run until there are no changes to be made, which can take a while if the size of the array is large. The next pass will sort the array and give us [3, 6, 17, 24, 52, 83], which is correctly sorted, however the algorithm doesn't know that and therefore has to run a second time in order to make sure that no changes can be made and therefore give us our sorted array.
This sorting algorithm is slow to perform especially with large datasets as the increase in size means there will be an increase in possible elements that need sorting. However, this algorithm is simple to implement and get a computer to carry out.
Bucket Sort
This algorithm works by grouping elements within an array into buckets (hence the name), then if the bucket contains more than one element, that bucket is sorted using another algorithm such as bubble sort. Once each bucket has been sorted, their elements are put back into the array in its sorted ordering.
For example, if we had an array [4, 32, 13, 6, 27, 35, 19, 38] the algorithm will group the elements like so:
0 - 9 [4, 6]
10 - 19 [19, 13]
20 - 29 [27]
30 - 39 [35, 32, 38]
then each group will use the bubble sort to give us:
0 - 9 [4, 6]
10 - 19 [13, 19]
20 - 29 [27]
30 - 39 [32, 35, 38]
from this we can recreate the array to finally give us:
[4, 6, 13, 19, 27, 32, 35, 38]
The bucket sort is quicker than the bubble sort but will struggle when trying to sort arrays that do not contain numbers as if its sorting based on letters, there is a decision that needs to be made on how the elements are grouped. Do you have one bucket for each letter or do you have a bucket for a group of letters i.e. A, B and C?
No comments:
Post a Comment