Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
JavaScript Return the lowest index at which a value should be inserted into an array once it has been sorted (either in ascending or descending order).
We have to write a function that returns the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted (either in ascending or descending order). The returned value should be a number.
For example, Let's say, we have a function getIndexToInsert() ?
getIndexToInsert([1,2,3,4], 1.5, 'asc') should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
Likewise,
getIndexToInsert([20,3,5], 19, 'asc') should return 2 because once the array has been sorted in ascending order it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).
Syntax
getIndexToInsert(array, element, order)
Parameters
- array ? The input array (can be unsorted)
- element ? The value to insert
- order ? Either 'asc' for ascending or 'desc' for descending (defaults to 'asc')
Algorithm Explanation
The function works by counting elements that are smaller and greater than the target element. For ascending order, we need the count of smaller elements (our insertion index). For descending order, we need the count of greater elements.
Example
const arr = [20, 3, 5];
const getIndexToInsert = (arr, element, order = 'asc') => {
const creds = arr.reduce((acc, val) => {
let { greater, smaller } = acc;
if(val
1
2
How It Works
Let's trace through the example with [20, 3, 5] and element 19:
- 20 > 19: greater = 1, smaller = 0
- 3 : greater = 1, smaller = 1
- 5 : greater = 1, smaller = 2
For ascending order: return smaller count (2). For descending order: return greater count (1).
Alternative Implementation Using Sort
const getIndexToInsertSort = (arr, element, order = 'asc') => {
const sortedArr = [...arr].sort((a, b) => order === 'asc' ? a - b : b - a);
for (let i = 0; i = sortedArr[i]) {
return i;
}
}
return sortedArr.length;
};
console.log(getIndexToInsertSort([1, 2, 3, 4], 1.5, 'asc'));
console.log(getIndexToInsertSort([20, 3, 5], 19, 'asc'));
1 2
Comparison
| Method | Time Complexity | Space Complexity | Approach |
|---|---|---|---|
| Counting Method | O(n) | O(1) | Count smaller/greater elements |
| Sort Method | O(n log n) | O(n) | Sort then find position |
Conclusion
The counting method is more efficient with O(n) time complexity compared to sorting. Both approaches correctly find the insertion index for maintaining sorted order.
