public static Coordinate FindElement2(int[][] matrix, Coordinate origin, Coordinate dest, int x) { if (!origin.Inbounds(matrix) || !dest.Inbounds(matrix)) { return null; } if (matrix[origin.row][origin.column] == x) { return origin; } else if (!origin.IsBefore(dest)) { return null; } /* Set start to start of diagonal and end to the end of the diagonal. Since * the grid may not be square, the end of the diagonal may not equal dest. */ Coordinate start = (Coordinate)origin.Clone(); int diagDist = Math.Min(dest.row - origin.row, dest.column - origin.column); Coordinate end = new Coordinate(start.row + diagDist, start.column + diagDist); Coordinate p = new Coordinate(0, 0); /* Do binary search on the diagonal, looking for the first element greater than x */ while (start.IsBefore(end)) { p.SetToAverage(start, end); if (x > matrix[p.row][p.column]) { start.row = p.row + 1; start.column = p.column + 1; } else { end.row = p.row - 1; end.column = p.column - 1; } } /* Split the grid into quadrants. Search the bottom left and the top right. */ return PartitionAndSearch(matrix, origin, dest, start, x); }