Skip to content

Instantly share code, notes, and snippets.

@brainyfarm
Last active August 8, 2016 15:03
Show Gist options
  • Save brainyfarm/bb38d757b862b72a1247eb1f9947e4fd to your computer and use it in GitHub Desktop.
Save brainyfarm/bb38d757b862b72a1247eb1f9947e4fd to your computer and use it in GitHub Desktop.
Olawale/FreeCodeCamp Algorithm: Where do I Belong
function getIndexToIns(arr, num) {
// Sort the array in ascending order
arr.sort( function( a, b ){ return a - b; } );
// Define a variable index to store the found index
var index;
// If the last item in the array is lesser in value than num
if(arr.indexOf( arr[ arr.length -1 ] ) < num ){
// Add one to the index of the last item and make it the index of num
index = arr.indexOf( arr[ arr.length -1 ] ) + 1;
}// End of if statement
// If it does not work as described up here
// Loop through the index of each element in the array up to the last element
for( i=0; i<arr.length; i++ ) {
// if num is greater than the current item and less than the next item
if( num > arr[ i ] && num < arr[ ( i + 1 ) ] ){
// Add one to the index of the current item and set it as the index we are looking for
index = i + 1;
} // End of if statement
// If the current item is equal to num
if( arr[ i ] === num ){
// Set the index of that item as the index we are looking for
index = i;
} // End of if statement
} // End of our loop
// Return the index
return index;
} // End of function
getIndexToIns([40, 60], 50);
/****
I feel stupid with the previous solution I did above
What was I even thinking while writing that?
***/
function getIndexToIns(arr, num) {
arr.push(num);
arr.sort(function(a,b){return a - b;});
return arr.indexOf(num);
}
getIndexToIns([20,3,5], 19);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment