2 - Sorting & Efficiency
How many ways can you sort a complete mess of numbers? Is there one fastest method? In this unit we will begin to build our library of useful functions, beginning with random number generators, then building randomized arrays, and finishing with common sorting algorithms.
2.1 - Random Library Functions
randChar(upperCase = true)
randString(maxLength, letterCase = 0)
arrayOfInts(length, min, max)
arrayOfStrings(length, maxStrLength, letterCase)
mixedArray(length, min, max, maxStrLength, letterCase)
Note: we are not permitted to use .sort( ), .reverse( ), .split( ), .join( ), or .includes( ). If you are unsure about any built-in functions ask the teacher.
2.1 - Hints
String.fromCharCode(num) will return a character from the ASCII table represented by 'num'
You can add to the end of a string (concatenation) but you can't modify the characters in a string.
Zero is usually a special case. You might need to take that into account, especially in randNum( ) because randNum(1) should return a number from 0 to 9.
To create an empty array variable:
Add an element to (or change) an array item:
.length gives the number of elements in the array
.push(x) will add 'x' to the end of an array (can be multiple items) and returns the new length.
.pop() will remove and return the last element.
.shift() will remove and return the first element, shifting all elements left one.
.unshift(x) will add 'x' to the beginning of the array (can be multiple items) and returns the new length.
A little heads up - Arrays in JS are passed & copied by reference
What does this mean - by reference?
It means that when you try to make a copy or pass an array into a function, it does not actually duplicate every item in the array to create separate arrays. It makes a link or shortcut to the array.
let origSheeps = ['🐑', '🐑'];
let sheeps2 = origSheeps;
// [ '🐑', '🐑', '🐺' ]
// [ '🐑', '🐑', '🐺' ]
😱 , our original sheeps have changed?!
2.2 - Hints
You will need a 'for' loop that goes through each item of the array starting at index 1 (the second element).
Begin looking left of that position and shift elements to the right (one-by-one) if they are larger than our temporary value.
Each time you finish looking left and insert the item, that is called a completed pass.
2.3 - Hints
You know how to swap items in an array from Insertion Sort.
shakerSort( ) is an adjustment of bubbleSort( )
Large items bubble right (odd #'d passes), small items bubble left (even #'d passes)
Reduce the length of each pass by 1 as items bubble to the appropriate end.
2.4 - Hints
By now you know how to go through an array and how to nest loops inside each other
You should know how to reduce the search window by 1, similar to Bubble (shaker) Sort
You should know how to swap items in an array
What else is there to know?