Bubble Sort

Bubble Sort is the simplest way in sorting algorithms. It maybe not be that efficient but as a beginner, it is a must to study it since it steps through a list, arranging it until it appears in the right order.

For example, arrange the numbers 5,3,1,4, and 2.

Let's do this step by step.

  1. Get the first two numbers (5 and 3). Is 5 greater than 3? Yes. Swap the numbers and it becomes 3,5,1,4,2
  2. 3 remains in the first spot after swapped by 5. Compare 5 and 1. Is five greater than 1? Yes. Swap both numbers and it becomes 3,1,5,4,2.
  3. Proceed to the next step by comparing 5 and 4. Is five greater than 4? Yes, then swap the two numbers and it becomes 3,1,4,5,2.
  4. Is five greater than 2? Yes, then swap. It becomes 3,1,4,2,5
As you've noticed, it is not in the right order yet. We need bubble sort to work on that.

The idea of bubble sort is: by the use of three variables and nested loops, you can work on this comparisons to store each value on each variable until the correct order displays.

No comments:

Post a Comment

Extended Search

Custom Search
Hello World