Let's populate an array with random integers:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
Every time we click the sort button, an algorithm processes the array, starting at the first element.
It compares the value at the element with index i with the value at element i+1 and if the value at i is bigger, it swaps them!
It keeps doing this until i reaches the second-last index in the array.
FOR i ← 0 TO LENGTH(numArray) - 2
IF numArr[i] > numArray[i+1] THEN
temp ← arr[i]
arr[i] ← arr[i+1]
arr[i+1] ← temp
END IF
END FOR
OUTPUT numArray
Can you see why we need to stop the loop at LENGTH(numArray) - 2 is this example?
Also, what do you notice at the end of each pass through the array - ie every time you press sort?
Using an IDE and high-level language of your choice, set up a scenario where an array of integers has been declared and initialised with values.
Create code using the above algorithm to process 1 pass through the array.
You should see that after this first pass, the largest number in the array will be found at the last index of the array.
Copy and paste your solution into your evidence document. Include any questions or observations you have about the algorithm.
How many times would we need to run the above algorithm until the array is fully sorted?
For example, if we have a small array, we could do this:
FOR i ← 0 TO 1000
sorting algorithm above
END FOR
Of course, we are probably doing some unnecessary processing. I am sure a small 10 element array will be sorted without needing 1001 passes!
Test your own ideas. How many times does the sorting algorithm need to be repeated before an array is full sorted?
Hint: to test an extreme situation, you could create an array sorted in descending order of value and see how many passes are required to sort it into ascending order of value eg
| 1000 | 900 | 800 | 700 | 600 | 500 | 400 |
Copy and paste your code into your evidence document and comment on any conclusions you have made.
Using your solution from Practical Activity #2, what do you notice for different data sets.
For example, test your algorithm for an array that is already sorted in ascending order of value eg.
| 45 | 77 | 99 | 104 | 120 | 123 | 129 |
Is your algorithm smart enough to realise that no sorting is required?
Research a more efficient Bubble Sort algorithm. It should stop processing the array when no more sorting is required and, during each pass, it should only process elements that need to be processed.
Use the Internet; use your textbook; use your creative, problem-solving mind.
Copy and paste your code into your evidence document and comment on any observations and/or conclusions you have made. Did you manage to create a program that efficiently bubble sorts an array of integers?
data type INTEGER pseudocode REAL program code DATE STRING CHAR bubble sort BOOLEAN declare variable