Created
January 15, 2017 22:22
-
-
Save SabrinaMarkon/12a0940d0a53bf2d0c906f0b08868a36 to your computer and use it in GitHub Desktop.
Sabrina Markon - Algorithms - We add a new integer to an existing array of integers, sort it using compare, then return the index of the first occurrence of the new element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sabrina: Notice how sort() includes a compare function. Since sort sorts by alphabetical order, sorting numbers tends to be WRONG. | |
The string "25" for example is GREATER THAN the string "100". So we compare with function(a,b) { return a-b; } to sort NUMBERS in | |
ASCENDING ORDER. (for descending order use return b-a instead). | |
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. | |
The returned value should be a number. | |
For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1). | |
Likewise, getIndexToIns([20,3,5], 19) should return 2 because once the array has been sorted it will look like [3,5,20] and | |
19 is less than 20 (index 2) and greater than 5 (index 1). | |
function getIndexToIns(arr, num) { | |
// Find my place in this sorted array. | |
arr.push(num); | |
arr.sort(function(a,b) { return a-b; }); | |
var position = arr.indexOf(num); | |
return position; | |
} | |
getIndexToIns([40, 60], 50); | |
TESTS: | |
getIndexToIns([10, 20, 30, 40, 50], 35) should return 3. | |
getIndexToIns([10, 20, 30, 40, 50], 30) should return 2. | |
getIndexToIns([40, 60], 50) should return 1. | |
getIndexToIns([3, 10, 5], 3) should return 0. | |
getIndexToIns([5, 3, 20, 3], 5) should return 2. | |
getIndexToIns([2, 20, 10], 19) should return 2. | |
getIndexToIns([2, 5, 10], 15) should return 3. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment