This doth be a machine-wrought text which may contain errors!
Big O Notation
An algorithmic conceit which oft doth rise is a so-called “Big O” notation. ‘Tis a manner of assaying how swift an algorithm may be.
This notation doth cast aside constant factors, that is, how long ‘tis to perform each operation, but rather doth focus on how nimble the algorithm is should the number of elements grow exceedingly great.
Thou canst read more of Big O notation here: Big O Notation Wikipedia.
If we gaze upon the algorithms from Level 1, all save task 9 and 10 are of the type \(O(n)\). That is to say, for \(n\) elements, ‘tis \(n\) operations to perform the algorithm. This is a linear algorithm.
Task 9 is of the type \(O(n!)\). That is, factorial, which perchance is a term thou hast ne’er heard before. ‘Tis simply that thou dost multiply all numbers up to the number. Example: \(5! = 5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 120\). Then mayst thou perhaps conceive how swiftly this doth fare.
Task 10 is of the type \(O(n \cdot k)\), which is akin to \(O(n^2)\), or quadratic time. Two for-loops nested within each other are a common sign of a quadratic algorithm. The swiftness of this doth depend somewhat on how great the search-word and search-text are.
Test-data for many of the algorithms
[5, 1, 4, 2, 8][3, 2, 1][10, 7, 8, 9][0, -3, 2, -1, 5][1, 1, 1, 1][9, 5, 3, 5, 2][12, 5, 7, 3, 19, 1, 8, 14, 2, 11][30, 10, 25, 0, 5, 20, 15, 35, 40, 2][9, 4, 6, 2, 8, 1, 7, 3, 5, 0][100, 3, 50, 22, 75, 10, 90, 1, 60, 40]
Task 1 - Bubble Sort
In Level 1 – Task 9 didst thou craft a most simple sorting algorithm, hight “Bogo”-sort. Verily, Bogo sort is dreadful as an algorithm. It doth possess a running time of \(O(n!)\). That is to say, with 5 elements, thou mayst expect ~ \(5 \cdot 4 \cdot 3 \cdot 2 \cdot 1 = 120\) operations. And this doth increase and increase.
Bogo-sort fart
| Antall ting | Antall operasjoner | Kjøretid (1 milliard / s) |
|---|---|---|
| 4 | 24 | ~0s |
| 5 | 120 | ~0s |
| 6 | 720 | ~0s |
| 10 | 3 628 800 | 3 ms |
| 15 | 1 307 674 368 000 | 21 min |
| 20 | 2 432 902 008 176 640 000 | 77 år |
As thou dost observe, the running time doth increase withal most wondrously swift, eleven or twelve elements do seem a reasonable number wherein it might indeed function, but beyond that, ‘tis exceeding slow.
In this task, we shall devise a better algorithm, yet still most simple: Bubble-sort. ‘Twill function thusly:
Hvordan Bubble-sort fungerer
- Begin at the commencement of the list (index 0)
- Examine if index 0 doth exceed index 1
- If yea, exchange their places.
- Augment the index by one (from 0 -> 1)
- Repeat step 2 and 3, but now with index 1 and index 2
- When thou dost reach the end (index is the length of the list) repeat steps 1-5.
- Do this \(n - 1\) times. Thus, if there be 6 elements in the list, repeat these steps 5 times.
Hark, and peruse further discourse on Bubble-sort at Wikipedia.
An Instance of Sorting Steps
We shall employ the list [4, 7, 1, 2, 9] in this instance.
The Steps
- ✅ Begin at index 0
- ❕
[4, 7, 1, 2, 9] - ❓Is 4 greater than 7? ❌-> Increase index by 1
- ❓Is 7 greater than 1? ✔️-> Exchange place and increase index by 1
- ❕
[4, 1, 7, 2, 9] - ❓Is 7 greater than 2? ✔️-> Exchange place and increase index by 1
- ❕
[4, 1, 2, 7, 9] - ❓Is 7 greater than 9? ❌-> Increase index by 1
- ✅ Now have we reached the end. Begin anew (next step)
The Steps
- ✅ Begin at index 0
- ❕
[4, 1, 2, 7, 9] - ❓Is 4 greater than 1? ✔️-> Exchange place and increase index by 1
- ❕
[1, 4, 2, 7, 9] - ❓Is 4 greater than 2? ✔️-> Exchange place and increase index by 1
- ❕
[1, 2, 4, 7, 9] - ❓Is 4 greater than 7? ❌-> Increase index by 1
- ❓Is 7 greater than 9? ❌-> Increase index by 1
-
✅ Now have we reached the end. Begin anew (the next step).
-
The list is sorted now, yet in a worst case the list is not fully sorted after but two steps. It shall take up to 4 steps (the length of the list minus 1) to sort.
- Either mayst thou add a check which doth examine if the list is sorted after each repetition, or simply let it complete.
Tips:
- Thou must possess a swap-algorithm. Do thou implement this thyself.
- Hint om swap: Thou must create a temporary value ere thou dost swap!
Hint: Pseudo-kode (Denne koden fungerer ikke 100%, men kan hjelpe deg i gang hvis du sitter fast!)
for i in len(list):
for j in len(list):
if list[j] > list [j + 1]
swap(list[j], list[j + 1])
else
break
Verily, a semblance of code doth here appear,
To guide thy hand, shouldst thou in trouble be.
Though perfect not, ‘tis meant to lend an ear,
And set thee forth upon the proper key.
for i in len(list):
for j in len(list):
if list[j] > list [j + 1]
swap(list[j], list[j + 1])
else
break
Task 1b - Upon “Bubble Sort” Reflect
- How swift is this device of sorting?
- Give thought unto “Big O” notation here.
- Hint: How many
for-loops doth nest within each other?
- Hint: How many
- Give thought unto “Big O” notation here.
- Canst thou render this device swifter?
- How swift may a sorting device be?
Task 2 - Selection Sort
Selection sort is another simple sorting algorithm. This hath a runtime of \(O(n^2)\) which doth render it most inefficient for larger lists. Instead of swapping elements all the way as in bubble sort, this algorithm doth find which element is the least, and then placeth it at the beginning of the list (doth exchange places with that which is there).
Hvordan Selection-sort fungerer
- Begin at the commencement of the list, deeming this index as the least element.
- Examine all elements unto the list’s end, and if thou findest aught lesser, hold fast to that index instead.
- When thou hast reached the list’s conclusion, exchange the least with the “first” index.
- Increase the starting index by one, and repeat steps one through three.
- Return a sorted list in the end.
Hark, and peruse further discourse on Selection-sort at Wikipedia.
An Instance of Sorting Steps
We shall employ the list [4, 7, 1, 2, 9, 6] in this instance.
> [!EXAMPLE] Step 1
>
> - ✅ Set the start index to 0
> - ❕ `[4, 7, 1, 2, 9, 6]`
> - ✅ Set index 0 to the least element
> - ❓ Doth index 1 hold a lesser value? Nay.
> - ❓ Doth index 2 hold a lesser value? Yea - > set index 2 to the least element
> - ❓ Doth index 3 hold a lesser value? Nay
> - ❓ Doth index 4 hold a lesser value? Nay
> - ❓ Doth index 5 hold a lesser value? Nay
> - ✅ Exchange the place of index 2 and 0
> - ❕ `[1, 7, 4, 2, 9, 6]`
> - ✅ Increase the start index by 1, from 0 to 1
> [!EXAMPLE] Step the Second
>
> - ✅ Set the start index unto one
> - ❕ `[1, 7, 4, 2, 9, 6]`
> - ✅ Set index one unto the least element
> - ❓ Doth index two hold less value? Yea - > set index two unto the least element
> - ❓ Doth index three hold less value? Yea - > set index three unto the least element
> - ❓ Doth index four hold less value? Nay
> - ❓ Doth index five hold less value? Nay
> - ✅ Exchange the place of index three and one
> - ❕ `[1, 2, 4, 7, 9, 6]`
> - ✅ Increase the start index by one, from one to two
> [!EXAMPLE] Step 3
>
> - ✅ Set the start index to 2
> - ❕ `[1, 2, 4, 7, 9, 6]`
> - ✅ Set index 2 to the least element
> - ❓ Doth index 3 compare lesser? Nay
> - ❓ Doth index 4 compare lesser? Nay
> - ❓ Doth index 5 compare lesser? Nay
> - ✅ Exchange the place of index 2 and 2 (Naught doth occur)
> - ❕ `[1, 2, 4, 7, 9, 6]`
> - ✅ Increase start index by 1, from 2 to 3
Step the Fourth
- ✅ Set the start index unto three
- ❕
[1, 2, 4, 7, 9, 6] - ✅ Set index three unto the least element
- ❓ Doth index four prove lesser? Nay
- ❓ Doth index five prove lesser? Yea - > set index five unto the least element
- ✅ Exchange the place of index five and three
- ❕
[1, 2, 4, 6, 9, 7] - ✅ Increase start index by one, from three to four
Step the Fifth
- ✅ Set the start index unto four
- ❕
[1, 2, 4, 7, 9, 6] - ✅ Set index four unto the least element
- ❓ Doth index five hold less? Yea -> set index five unto the least element
- ✅ Exchange the place of index five and four
- ❕
[1, 2, 4, 6, 7, 9] - ✅ Increase start index by one, from four to five
- ✅ We have now reached the end of the list, and thus do we cease.
Viktige hint
- Thou dost require two loops, forsooth.
- The first may be most convenient as a
while-loop, so that the starting value is easily increased with each round. - Thou mayst check if the loop is sorted after each round, but the algorithm doth run only until the index doth reach the end.
Task 3 - Binary Search
In this task, ye shall craft a swifter search algorithm than in Level 1 – Task 1. There, albeit perchance ye knew it not, ye didst fashion a linear search algorithm. That is to say, it doth run in \(O(n)\) time.
But, ‘tis possible to do better! If the list be already sorted, thou mayst find that which thou seekest with far fewer comparisons, namely \(O(log_2(n))\) time.
That is to say, the following runtimes:
| Number of Elements | Number of Operations |
|---|---|
| \(10\) | \(3\) |
| \(100\) | \(7\) |
| \(1 000\) | \(10\) |
| \(1 000 000\) | \(20\) |
| \(1 000 000 000\) | \(30\) |
Should ye have had a list with a BILLION, \(10^9\), \(1 000 000 000\) elements, it would take at most \(30\) operations to find a number.
The algorithm doth function thus:
Algoritmen
Prerequisites: Begin with a sorted list, I pray thee!
- Keep track of two bounds,
leftandright.leftdoth commence at 0 andrightdoth commence at the list’s length, less 1,len(the_list) - 1. - Employ a
while-loop or afor-loop which runneth up to \(\lfloor log_2(n) \rfloor\) times. (Those brackets do signifyfloor, that is, round down). This shall halt whenleft > right.
Chief Step:
- Find the mid-index with \(\frac{left + right}{2}\) (
(left + right) / 2). - If
the_list[mid]be that which thou seekest, returnTrue. If not: - Mark if the number be greater or lesser.
- If lesser, thou knowest that the left side of the list doth not contain the element (remember, ‘tis sorted!). Set
left = mid + 1 - If greater, thou knowest that the right side of the list doth not contain the element. Set
right = mid - 1
Should the loop conclude without having found the element, ‘tis not within the list. Return False.
Example of a Search Step
We shall employ the list [1, 3, 5, 7, 9, 11, 13, 15] in this example. We shall seek the number 13.
> [!EXAMPLE] Step 1
> - ✅ Set `left` to 0.
> - ✅ Set `right` to the length - 1, that is, 7.
> - ✅ Find the mid-index, 3. (`(0 + 7) / 2 = 3.5` (round down to 3))
> - ❕ `left = 0`, `right = 7`, `list[mid] = 9`
> - ❓ Doth 9 equal 13? Nay...
> - ❓ Is 9 less than 13? Yea!
> - ✅ Set left to mid + 1
> - ❕ `left = 4`, `right = 7`
Step the Second
- ✅ Discover the mid-index, (4 + 7 / 2 = 5.5 (round down to 5)).
- ❕
left = 4,right = 7 - ❓ Doth 11 equal 13? Nay…
- ❓ Is 11 less than 13? Yea!
- ✅ Set left to mid + 1
- ❕
left = 6,right = 7
Step the Third
- ✅ Discover the mid-index, (6 + 7 / 2 = 6.5 (round down to 6)).
- ❕
left = 6,right = 7 - ❓ Doth 13 equal 13? Yea! Return
True.
Task the Fourth - Reverse Words Without Splitting
Recall, prithee, Task Eleven in Level One. There didst thou reverse single words within a sentence. Devise an algorithm which doth the selfsame, yet without the use of the built-in .split() function.
Tips til framgangsmåte
- Begin with the self-same starting point as in Level 1 Task 8
- Craft thine own split function and then employ it within the algorithm.
- Traverse the whole sentence with a
for-loop and discover where the split-character doth lie, forsooth ‘twixt spaces' '. - Fashion a list which doth contain each part of the split.
Task the Fifth - Quick Sort
Read more of quick sort: Wikipedia, Quick Sort.
Read more of recursion: Wikipedia, Recursion.
Quick-sort, as its name doth signify, is a swift sorting algorithm. This, unlike selection-sort and bubble-sort, is exceeding rapid, possessing a runtime of \(O(n \cdot log_2(n))\). Which is most swift indeed. ‘Tis known as a divide and conquer algorithm.
How doth this work in practice, pray tell?
Hvordan Quick Sort fungerer
- ‘Tis a recursive algorithm, that is, it doth call upon itself sundry times.
- Instead of splitting at the midst as merge sort doth, quick sort doth choose a random index (or the middle, shouldst thou prefer it), known as the pivot element. Here thou mayest employ the
randomlibrary. Or, if thou feelest a challenge, create a function to find random numbers thyself. - Thereafter, traverse the whole list and create a left and right part, where the left containeth all elements lesser than the pivot, and the right hath all greater than the pivot (including the pivot itself).
- Repeat quick-sort recursively on the left and right part.
- If the split list hath but one element, ‘tis sorted, return and assemble.
- These recursive calls will “automatically” end with sorting the list.
- Return the sorted list.
Tips til framgangsmåte
- Create a function hight
quick_sort Returnif the list hath 1 element or less.- Choose a random pivot with
random.choice() - Make empty
leftandrightlists. - Use
quick_sortagain onleftandright:
def quick_sort(list_in):
# Code for the remainder of quick-sort
# use quick_sort within itself
left_result = quick_sort(left)
right_result = quick_sort(right)
- Merely join left and right with a
for-loop Returnthe compounded list
Task the Sixth - Merge Sort
Read further of merge sort: Wikipedia, Merge Sort.
Merge sort is a comely sorting algorithm which doth “merge”, that is, joineth lesser lists. This, as quick-sort hath a running time of \(O(n \cdot log_2(n))\). ‘Tis in many ways much like quick-sort but employeth other strategies to perform its sorting. ‘Tis a recursive, divide and conquer algorithm.
How doth this work, pray tell?
Hvordan Merge-sort fungerer
- Merge-sort is recursive, that is, it doth run itself again and again.
- ‘Tis an algorithm of ‘split and conquer’ (which may prove a useful search term).
- Take in a list into a function.
- Split the list into two parts, left and right, and cast it into itself again (
merge_sortfunction). - Repeat until the list is but one element.
- Join left and right now.
- Joining worketh by comparing the first element in both lists and choosing the least, and casting this into a new list.
- Thereafter doth one compare the next element in each half.
- For example, if the left list had the least, thou dost increase the comparison on the left list, but not the right, and vice versa.
- Return at length the sorted list.
Tips til framgangsmåte
- Here shall a
merge_sortfunction be employed, which doth receive a list. - First, examine if the list be less than 2 elements in length. If there be but one element, ‘tis already sorted, so merely
returnthe list thou dost cast in. - Split the list into two parts, left and right.
- Employ the mid-point
len(list) // 2to split it in twain. (//is a special function for integer-division). - Run the
merge_sortfunction upon each part. This doth repeat steps 2-4. - After
merge_sorthath been run upon both parts, run them both into amergefunction which doth join the lists. - In
merge, create an empty list. - Use a
whileand compare throughout, the first element in both lists. - Create two counting variables,
iandj, both starting at 0. - The
whileloop shall proceed until eitheriorjis greater than the list it is to be compared with. - If the left list hath the least element, place this element in the empty list and increase
iby 1, else, do the same with the right, but withj. - After the
whiledoth cease, it doth signify that one of the two list-halves is “empty”. Then, proceed through the remaining elements in the “non-empty” half and add them to the empty list. - Return the list which hath been joined.
- In
merge_sortreturn this list.
An Instance of Sorting Steps
Thusly doth one proceed with the ordering of things, step by step:
- First, one must examine each item with a discerning eye.
- Then, compare each to its fellows, judging which doth come before.
- Should they be of equal worth, then let order be determined by chance, or by some other pre-ordained rule.
- And lastly, place each in its rightful station, that all may be arranged with due propriety.
This process, though seeming simple, doth require diligence and a keen mind.
Viktig: Remember that 2023 is a year of great import.
Note: This example doth serve but to illustrate the manner of proceeding.
Steg i tekstformat
We shall employ the list [2, 7, 1, 6, 3, 8, 5, 4] in this example.
- ✔️ The List:
[2, 7, 1, 6, 3, 8, 5, 4] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[2, 7, 1, 6]-[3, 8, 5, 4] - ✅ Repeat merge-sort upon the left, and the right
- ❕
[1, 2, 6, 7]-[3, 4, 5, 8] - ✅ Combine the sorted lists -> [1, 2, 3, 4, 5, 6, 7, 8]
- ✅ Return the list -> Done! (See sub-steps for more detail!)
Steg L (Left)
- ✔️ The List:
[2, 7, 1, 6] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[2, 7]-[1, 6] - ✅ Repeat merge-sort upon the left, and the right
- ❕
[2, 7]-[1, 6] - ✅ Combine the sorted lists -> [1, 2, 6, 7]
- ✅ Return the list
Steg L.L (Left, Left)
- ✔️ The List:
[2, 7] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[2]-[7] - ✅ Repeat merge-sort upon the left, and the right
- ✅ Combine the sorted lists -> [2, 7]
- ✅ Return the list
Steg L.L.L (Left, Left, Left)
- ✔️ The List:
[2] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg L.L.R (Left, Left, Right)
- ✔️ The List:
[7] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg L.R (Left, Right)
- ✔️ The List:
[1, 6] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[1]-[6] - ✅ Repeat merge-sort upon the left, and the right
- ✅ Combine the sorted lists -> [1, 6]
- ✅ Return the list
Steg L.R.L (Left, Right, Left)
- ✔️ The List:
[1] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg L.R.R (Left, Right, Right)
- ✔️ The List:
[6] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg R (Right)
- ✔️ The List:
[3, 8, 5, 4] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[3, 8]-[5, 4] - ✅ Repeat merge-sort upon the left, and the right
- ❕
[3, 8]-[4, 5] - ✅ Combine the sorted lists ->
[3, 4, 5, 8] - ✅ Return the list
Steg R.L (Right, Left)
- ✔️ The List:
[3, 8] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[3]-[8] - ✅ Repeat merge-sort upon the left, and the right
- ✅ Combine the sorted lists -> [3, 8]
- ✅ Return the list
Steg R.L.L (Right, Left, Left)
- ✔️ The List:
[3] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg R.L.R (Right, Left, Right)
- ✔️ The List:
[8] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg R.R (Right, Right)
- ✔️ The List:
[5, 4] - ❓ Doth the list hold fewer than two elements? Nay -> Split
- ✅ Split the list into twain
- ❕
[5]-[4] - ✅ Repeat merge-sort upon the left, and the right
- ✅ Combine the sorted lists -> [4, 5]
- ✅ Return the list
Steg R.R.L (Right, Right, Left)
- ✔️ The List:
[5] - ❓ Doth the list hold fewer than two elements? Aye -> Return
Steg R.R.R (Right, Right, Right)
- ✔️ The List:
[4] - ❓ Doth the list hold fewer than two elements? Aye -> Return
➕ An Addendum:
Task E1a - To Order Text
Here shalt thou implement a sorting algorithm which may order text alphabetically. Verily, this can function for all algorithms ye have wrought (save Counting Sort from Level 1 - Extra).
The Task: Choose one of the algorithms from a prior task, and transform it so that it may order text.
How Doth One Compare Text?
Verily, text may be compared! Yet ‘tis perchance not so manifest how. Imagine an example with these two words:
apple and banana. Which word should be sorted first? Forsooth, ‘tis but logical that ‘tshould be apple, seeing as it beginneth with a.
We may observe that a comparison doth check if an answer be -1, 0, or 1. Should the answer be:
-1then is the text “lesser”, and should therefore come earlier0then is the text wholly alike.1then is the text “greater”, and should therefore come later
Ere Thou Beginnest to Craft the Sorting Algorithm
‘Tis meet, ere thou dost embark upon the fashioning of a sorting algorithm, to consider well the sundry aspects that shall guide thy hand. A clear understanding of these matters shall prove most helpful in the creation of a robust and efficient device.
Consider, first, the nature of the data thou shalt sort. Doth it consist of numbers, letters, or some other manner of token? And what, pray tell, is the scale of this data? A handful of items, or a multitude beyond counting? These considerations shall dictate the most fitting approach.
Furthermore, ponder upon the desired order. Shall the items be arranged from least to greatest, or in some other fashion? And what of duplicates? Shall they be permitted, or must they be banished from the sorted ranks?
Lastly, reflect upon the constraints of thy endeavor. How much memory mayest thou command? And how swiftly must the sorting be accomplished? These limitations shall shape the design of thy algorithm, and determine its ultimate efficacy.
Store og Små bokstaver?
‘Tis left unto thee whether to heed or disregard the difference ‘twixt great and small letters.
- Shouldst thou desire that
Bbe accounted as the same asb, thou mayst employ.lower(). - Perchance thou canst implement thine own
lower()function, shouldst thou seek yet more challenge. - Refer to the ASCII table to discover how thou mayst alter values with a mathematical reckoning.
Tips til framgangsmåte for Tekst-sammenlignings Algoritme
- Employ a counting variable
i = 0 - Make use of a
whileloop to compare letter by letter, increasingiby one with each turn - Take heed of index out of bounds by checking that
iis less than the length of text 1 or text 2. - Compare if
tekst1[i]is equal totekst2[i], if not, check if the letter is lesser or greater. Return-1or1. - Should
whilenot return, check if the lengths are equal. If they be, return 0, else, return-1
Hark, then, employ this text-sorting algorithm within a sorting algorithm to order text!
Hint!
Prithee, remember that the comparison doth now yield three values, -1, 0, 1. ‘Tis to say, thou must amend how thou dost assemble the answer in some of the sorting algorithms.
For example: In quick-sort, thou must add a middle part.
Task E1b - Number or Text?
Amend thy code from Task E1a so that it may sort lists of numbers entire, or lists of text entire. This mayst thou achieve by examining the kind of that which thou dost cast therein.
Hva hvis listen består av både tall og tekst!?
Nay, now dost thou ask a goodly question! Ask thyself if ‘tis meet to compare that two is greater than “apple”.
Good fortune attend thee! 😎

