Guest User

Untitled

a guest
Oct 21st, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. function searchElementInSortedMatrix(matrix, inputX)
  2. {
  3. let result = { row: -1, col: -1 };
  4.  
  5. // Определим индекс ближайшего к середине элемента
  6. let indexInMiddle = Math.floor(matrix[0].length / 2) - 1;
  7.  
  8. // Пройдем по массиву с самого конца, так как массив уже изначально отсортирован
  9. for (let i = matrix.length - 1; i > -1; i--)
  10. {
  11. // Проверим первый элемент строки, чтобы узнать, интересна ли она нам для проверки
  12. if (inputX >= matrix[i][0])
  13. {
  14. // Определим справа или слева от середины наш элемент
  15. if (matrix[i][indexInMiddle] > inputX) // справа
  16. {
  17. for(let y = 0; y <= indexInMiddle; y++)
  18. {
  19. if (matrix[i][y] === inputX)
  20. {
  21. result.row = i;
  22. result.col = y;
  23. return result;
  24. }
  25. }
  26. }
  27. else // слева
  28. {
  29. for (let y = indexInMiddle; y < matrix[i].length; y++)
  30. {
  31. if (matrix[i][y] === inputX)
  32. {
  33. result.row = i;
  34. result.col = y;
  35. return result;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. return result;
  42. }
  43.  
  44. const matrix = [
  45. [ 1, 5, 10, 20 ],
  46. [ 7, 9, 15, 28 ],
  47. [ 12, 25, 30, 36 ],
  48. [ 22, 35, 45, 50 ]
  49. ];
  50.  
  51. console.info(searchElementInSortedMatrix(matrix, 1));
Add Comment
Please, Sign In to add comment