forked from roytuts/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
find-start-and-end-index-of-element-in-array/StartAndEndIndexOfValueInArray.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |