Arrays - Example 5a

This example sorts the numbers in the array without using sort(). Instead, it defines a function called bubble_sort() which sorts the numbers the hard way. Again, it displays the original array on the left and the sorted version on the right.

The program uses the Math.random() function to generate random numbers. Unfortunately, these are decimal values, so we need the Math.floor() function to round them down to whole numbers.

The program contains a function which uses the famous Bubble Sort algorithm to sort the numbers. This goes through all the numbers several times, and every time it finds two adjacent numbers which are out of order, it swaps them over. By the time it has passed through the numbers once, the largest one has "bubbled" to the end of the list. By the end of the next pass through the numbers, the penultimate element also contains the largest-but-one value etc. This is why it is called Bubble Sort - the numbers move gradually towards the end like bubbles rising in a glass of lemonade.

Feel free to copy the definition of function bubble_sort() into your own programs. It should work without any change as long as you give it the array to be sorted as a parameter.



Go Back