![]() |
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted Array
Method 1: Using Linear SearchLinear search is a type of brute force method that works on linear traversal of the array. It searches the target in O(N) time. It works whether the array is sorted or not. The program will run till the target is not found and will stop when the Last occurrence is matched. Example: In this example. we will use linear search to get the last index of the target element. Javascript
Output
Last occurrence of 5 is at the index: 6 Method 2: Using Linear Search (Reverse order)This method is similar to the above, the only difference is we will iterate the array in reverse order i.e. from last index to first. Example: In this method, we will use the reverse iteration in linear search to get the last occurance of target element. Javascript
Output
The Last index of 5 is: 6 Method 3: Using Binary SearchIn this method, we will use Binary search to get the first occurance of target element. Binary search is an optimized technique which give output in O(log N) time. It works only for the sorted data. Using binary search if target element is found we will try to search the last occurrence in the right half again and provide the reuired output. Example: In this example, we will use binary search to get the desired output. Javascript
Output
Last index of 5 is at index: 6 Method 4: Using array.lastIndexOf() methodIn this approach, we will use array.lastIndexOf() method. The JavaScript Array lastIndexOf() Method is used to find the index of the last occurrence of the search element provided as the argument to the function. Syntax:array.lastIndexOf(element, start)
Example: In this example, we will use arr.indexOf() method to find the last occurrence of target element Javascript
Output
Last index of 8 is at index: 11 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |