Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function searchElementInSortedMatrix(matrix, inputX)
- {
- let result = { row: -1, col: -1 };
- // Определим индекс ближайшего к середине элемента
- let indexInMiddle = Math.floor(matrix[0].length / 2) - 1;
- // Пройдем по массиву с самого конца, так как массив уже изначально отсортирован
- for (let i = matrix.length - 1; i > -1; i--)
- {
- // Проверим первый элемент строки, чтобы узнать, интересна ли она нам для проверки
- if (inputX >= matrix[i][0])
- {
- // Определим справа или слева от середины наш элемент
- if (matrix[i][indexInMiddle] > inputX) // справа
- {
- for(let y = 0; y <= indexInMiddle; y++)
- {
- if (matrix[i][y] === inputX)
- {
- result.row = i;
- result.col = y;
- return result;
- }
- }
- }
- else // слева
- {
- for (let y = indexInMiddle; y < matrix[i].length; y++)
- {
- if (matrix[i][y] === inputX)
- {
- result.row = i;
- result.col = y;
- return result;
- }
- }
- }
- }
- }
- return result;
- }
- const matrix = [
- [ 1, 5, 10, 20 ],
- [ 7, 9, 15, 28 ],
- [ 12, 25, 30, 36 ],
- [ 22, 35, 45, 50 ]
- ];
- console.info(searchElementInSortedMatrix(matrix, 1));
Add Comment
Please, Sign In to add comment