Weeks 3&4 - Arrays & Sorting
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
We will build a library for ourselves that contains useful functions. Look for the Helper Library project in our new Repl.it course (see 3.0 above).
- randInt(min, max, inclusive = true)
- round(number, precision)
- randChar(letterCase = 1)
- randString(maxLength, letterCase = 0)
Important: Do not use .toFixed() as it does not round correctly.
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 (called concatenation)
- Math.pow(), Math.round() and Math.random() will be your friends.
- If you want a random number 4 digits long, that is a random number between 1000 and 9999 inclusive. Interesting fact: 9999 = 10 000 - 1
- Zero is usually a special case. You might need to take that into account, especially in randNumOfLength( ) because randNumOfLength(1) should return a number from 0 to 9.
2.2 - Array Library Functions
Now let's create some functions that deal with arrays.
First - at the top of your code document, just after the heading comment block, add the following line exactly:
- inArray(item, array)
- arrayOfInts(length, min, max, inclusive, allowDuplicates)
- arrayOfStrings(length, 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.2 - Hints
- Create an empty array variable:
- Add an element to (or change) an array:
- .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 return 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 return the new length.
2.3 - 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.4 - Hints
- You know how to swap items in an array from Insertion Sort.
- shakerSort( ) is an adjustment of bubbleSort( )
- Reduce the length of each pass by 1 as items bubble to the appropriate end.
2.5 - Hints
- You should know how to go through an array
- You should know how to reduce the search window by 1, similar to Bubble Sort
- You should know how to swap items in an array