Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
roytuts authored Sep 2, 2019
1 parent fdf5137 commit 9fdfbf2
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
public class StartAndEndIndexOfValueInArray {

public static void main(String[] args) {
int[] arr = new int[] { 1, 1, 2, 2, 3, 3, 3, 3, 3, 5, 8, 6, 9 };
StartAndEndIndexOfValueInArray findIdx = new StartAndEndIndexOfValueInArray();
int totalElements = arr.length;
int startIndex = findIdx.findStartIndex(arr, 0, totalElements, 3);
int endIndex = findIdx.findEndIndex(arr, 0, totalElements, 3, totalElements);
System.out.println("Start Index: " + startIndex + ", End Index: " + endIndex);
}

private int findStartIndex(int[] arr, int low, int high, int x) {
if (high > low) {
int mid = low + (high - low) / 2;
if ((mid == 0 || x > arr[mid - 1]) && x == arr[mid]) {
return mid;
} else if (x > arr[mid]) {
return findStartIndex(arr, mid + 1, high, x);
} else {
return findStartIndex(arr, low, mid - 1, x);
}
}
return -1;
}

private int findEndIndex(int[] arr, int low, int high, int x, int totalElements) {
if (high > low) {
int mid = low + (high - low) / 2;
if ((mid == totalElements - 1 || x < arr[mid + 1]) && x == arr[mid]) {
return mid;
} else if (x < arr[mid]) {
return findEndIndex(arr, low, mid - 1, x, totalElements);
} else {
return findEndIndex(arr, mid + 1, high, x, totalElements);
}
}
return -1;
}
}
1 change: 1 addition & 0 deletions find-start-and-end-index-of-element-in-array/readme.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
You can read tutorial at https://www.jeejava.com/find-start-and-end-index-of-a-given-element-in-a-sorted-array/

0 comments on commit 9fdfbf2

Please sign in to comment.