Java Exercises: Find the index of a value in a sorted array.
Java Basic: Exercise-124 with Solution
Write a Java program to find the index of a value in a sorted array. If the value does not find return the index where it would be if it were inserted in order.
Example:
[1, 2, 4, 5, 6] 5(target) -> 3(index)
[1, 2, 4, 5, 6] 0(target) -> 0(index)
[1, 2, 4, 5, 6] 7(target) -> 5(index)
Pictorial Presentation:
Sample Solution:
Java Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
int[] nums = {1,2,4,5,6};
int target;
target = 5;
// target = 0;
// target = 7;
System.out.print(searchInsert(nums, target));
}
public static int searchInsert(int[] nums1, int target) {
if (nums1 == null || nums1.length == 0) {
return 0;
}
int start = 0;
int end = nums1.length - 1;
int mid = start + (end - start)/2;
while (start + 1 < end) {
mid = start + (end - start)/2;
if (nums1[mid] == target) {
return mid;
} else if (nums1[mid] > target) {
end = mid;
} else {
start = mid;
}
}
if (nums1[start] >= target) {
return start;
} else if (nums1[start] < target && target <= nums1[end]) {
return end;
} else {
return end + 1;
}
}
}
Sample Output:
3
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to find the subarray with smallest sum from a given array of integers.
Next: Write a Java program to get the preorder traversal of its nodes' values of a given a binary tree
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework