Difference between revisions of "W1352 Bubble Sort"

From Coder Merlin
m (Editorial review and minor corrections)
 
(13 intermediate revisions by 4 users not shown)
Line 1: Line 1:
[[File:DRAFT ICON.png|DRAFT ICON]]
[[File:Reflection in a soap bubble edit.jpg|thumb|link=|Reflection in a soap bubble]]
== Background ==
* Read [https://en.wikipedia.org/wiki/Bubble_sort Bubble Sort] (Wikipedia)
* View [https://www.youtube.com/watch?v=gaC4MKqn41g Bubble Sort 1- Algorithm] (YouTube)
* View [https://www.youtube.com/watch?v=18OO361--1E Bubble Sort Algorithm] (YouTube)


== Research ==
== Algorithm ==
* Read [https://en.wikipedia.org/wiki/Bubble_sort Bubble Sort (Wikipedia)]
The bubble sort algorithm is one of the simplest sorting algorithms. Here's an overview of how it works:
* View [https://www.youtube.com/watch?v=nmhjrI-aW5o Bubble Sort (Geeks for Geeks)]


# Iterate, with an index, over all array elements.
# If the element on the left is '''greater than''' the element on the right, swap the elements.
# Repeat steps 1 & 2 until there are no more swaps to complete.


== Exercises ==
=== Implementation ===
# Practice with Playing Cards
Although the algorithm is simple, the implementation takes a bit more thought. Here are some things to keep in mind:
## Shuffle a “deck” of 13 cards.
 
## Lay out every card in the deck, horizontally, face-up, from left-to-right.
* You'll need a variable to count the number of swaps you've made, in total and after each pass.
## Record the ordering of the deck on a tracking sheet.
* Before a swap, you'll need to store one of the values in a '''temporary variable'''.
## Place a two-headed pointer on the left-hand side so that it’s pointing at the first and second card.
* You'll need a '''nested loop''' (the outer loop to continue until the array is sorted, and the inner loop to iterate over the array).
## If the first card is greater in value than the second card, swap the two cards. If a swap occurs, make a tick mark on the tracking sheet.
* Consider which type of loop is the best option. ('''Hint:''' you'll need the outer loop to always run at least once.)
## Whether a swap occurred or not, advance the pointer forward (to the right) by one card, so that it’s now pointing at the second and third cards.
 
## Again make a comparison following the above rules for swapping.
==== Swaps ====
## Continue to track any swaps that occur and advance the pointer until reaching the right-end side of the deck.
You can write the swap implementation within the nested loop or within a separate function. Note that if you choose to write a separate function, you'll want to pass the array into the function '''by reference''' to avoid making a copy of the array each time you need to make a swap. However, you choose to implement the swap, you'll need to store at least one of the values (the left or the right) outside the array. If you just swap without storing one of the values:
## At this point, the first pass has completed. Record the number of swaps that occurred during this pass.
 
## If any swaps occurred during the pass, begin a new pass by repeating this procedure, moving the pointer back to the beginning on the far, left-hand side and moving to the right again.
<syntaxhighlight>
## When no swaps have occurred during a pass, you’re done.
integers[index-1] = integers[index]
# Complete Merlin exercise 1851
integers[index] = integers[index-1]
=== Quiz ===
</syntaxhighlight>
 
After the above code executes, the elements/integers at '''''index''''' and '''''index - 1''''' would be equal to whatever the element/integer at '''''index''''' originally was. To solve this, you'll need to store either initial element into a temporary variable, swap the elements, then assign the remaining element to your stored value.
 
=== Example ===
Here's an example of a bubble sort for an array with 3 elements:
 
<syntaxhighlight>
Array: [42, 82, 40] | Initial, Pass: 0
Array: [42, 40, 82] | Swaps: 1, Pass: 1
Array: [40, 42, 82] | Swaps: 1, Pass: 2
Array: [40, 42, 82] | Swaps: 0, Pass: 3
Sorted in 3 iterations
</syntaxhighlight>
 
Iteration #
# The array was initially set to <syntaxhighlight inline>[42, 82, 40]</syntaxhighlight>. Remember that we compare each element with the one before it, so the algorithm compares '''42''' and '''82''' first. Since 42 < 82, there's nothing to swap. However, for the next two elements '''82''' and '''40''', 82 > 40, so the elements are swapped.
# For the second iteration, the array starts at <syntaxhighlight inline>[42, 40, 82]</syntaxhighlight>. The first two elements, '''42''' and '''40''' are compared. Because 42 > 40, the first two elements are swapped. Then, the next two elements: '''42''' and '''82''' are compared. Because 42 < 82, they are already in order and no swaps need to be made.
# For the third iteration, the array start at <syntaxhighlight inline>Array: [40, 42, 82]</syntaxhighlight>. The first two elements, '''40''' and '''42''' are compared. Because 40 < 42, no swaps need to be made. Then, the next two elements, '''42''' and '''82''' are compared. Because 42 < 82, no swaps need to be made. Because no swaps were made at all in this iteration, we know the array is sorted and we can exit the loop.
 
=== Performance ===
Although bubble sort is a simple algorithm to implement, it is rarely used for real-world applications because of its poor performance ( O(n^2) ) and is usually seen in an academic environment.
 
== Quiz ==
<quiz shuffleanswers=true display=simple>
<quiz shuffleanswers=true display=simple>
{
{
Line 115: Line 144:


</quiz>
</quiz>
== Exercises ==
{{Exercises|
* {{MMMAssignment|M1352-10}}
}}

Latest revision as of 17:29, 15 November 2023

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Reflection in a soap bubble

Background[edit]

Algorithm[edit]

The bubble sort algorithm is one of the simplest sorting algorithms. Here's an overview of how it works:

  1. Iterate, with an index, over all array elements.
  2. If the element on the left is greater than the element on the right, swap the elements.
  3. Repeat steps 1 & 2 until there are no more swaps to complete.

Implementation[edit]

Although the algorithm is simple, the implementation takes a bit more thought. Here are some things to keep in mind:

  • You'll need a variable to count the number of swaps you've made, in total and after each pass.
  • Before a swap, you'll need to store one of the values in a temporary variable.
  • You'll need a nested loop (the outer loop to continue until the array is sorted, and the inner loop to iterate over the array).
  • Consider which type of loop is the best option. (Hint: you'll need the outer loop to always run at least once.)

Swaps[edit]

You can write the swap implementation within the nested loop or within a separate function. Note that if you choose to write a separate function, you'll want to pass the array into the function by reference to avoid making a copy of the array each time you need to make a swap. However, you choose to implement the swap, you'll need to store at least one of the values (the left or the right) outside the array. If you just swap without storing one of the values:

integers[index-1] = integers[index]
integers[index] = integers[index-1]

After the above code executes, the elements/integers at index and index - 1 would be equal to whatever the element/integer at index originally was. To solve this, you'll need to store either initial element into a temporary variable, swap the elements, then assign the remaining element to your stored value.

Example[edit]

Here's an example of a bubble sort for an array with 3 elements:

Array: [42, 82, 40] | Initial, Pass: 0 
Array: [42, 40, 82] | Swaps: 1, Pass: 1
Array: [40, 42, 82] | Swaps: 1, Pass: 2
Array: [40, 42, 82] | Swaps: 0, Pass: 3
Sorted in 3 iterations

Iteration #

  1. The array was initially set to [42, 82, 40]. Remember that we compare each element with the one before it, so the algorithm compares 42 and 82 first. Since 42 < 82, there's nothing to swap. However, for the next two elements 82 and 40, 82 > 40, so the elements are swapped.
  2. For the second iteration, the array starts at [42, 40, 82]. The first two elements, 42 and 40 are compared. Because 42 > 40, the first two elements are swapped. Then, the next two elements: 42 and 82 are compared. Because 42 < 82, they are already in order and no swaps need to be made.
  3. For the third iteration, the array start at Array: [40, 42, 82]. The first two elements, 40 and 42 are compared. Because 40 < 42, no swaps need to be made. Then, the next two elements, 42 and 82 are compared. Because 42 < 82, no swaps need to be made. Because no swaps were made at all in this iteration, we know the array is sorted and we can exit the loop.

Performance[edit]

Although bubble sort is a simple algorithm to implement, it is rarely used for real-world applications because of its poor performance ( O(n^2) ) and is usually seen in an academic environment.

Quiz[edit]

1 Bubble sort is too slow and impractical for most problems.

True
False

2 Bubble sort is most practical if:

The set of elements is very large
Elements are already sorted in reverse order
Doubles (floating point types) are used rather than integers
Elements are in nearly sorted order

3 One advantage of bubble sort is that the ability to detect that the list is sorted is built into the algorithm.

True
False

4 An element that must move toward the end of the list can move quickly because it can take part in successive swaps.

False
True

5 An element that must move toward the beginning of the list can move faster than one step per pass.

True
False

6 Elements move toward the beginning of the list very quickly.

True
False

7 Consider the list: 5 1 4 2 8
After the first swap, the list will be:

1 5 4 2 8
1 4 2 5 8
1 2 4 5 8
1 4 5 2 8

8 Consider the list: 5 1 4 2 8
After the second swap, the list will be:

1 2 4 5 8
1 4 5 2 8
1 4 2 5 8
1 5 4 2 8

9 Consider the list: 5 1 4 2 8
After the third swap, the list will be:

1 4 2 5 8
1 4 5 2 8
1 5 4 2 8
1 2 4 5 8

10 Consider the list: 5 1 4 2 8
After the first pass, the list will be:

1 4 2 5 8
1 5 4 2 8
1 4 5 2 8
1 2 4 5 8

11 Consider the list: 5 1 4 2 8
After the second pass, the list will be:

1 2 4 5 8
1 4 2 5 8
1 4 5 2 8
1 5 4 2 8

12 Consider the list: 5 1 4 2 8
How many passes are required before the algorithm terminates?

Four
Three
Two
Five

Exercises[edit]

ExercisesExercisesIcon.png
  •  M1352-10  Complete  Merlin Mission Manager  Mission M1352-10.