How to use Linear Search (Reverse order) In Javascript
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
// Input array arr = [1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9]; // Target element target = 5; // Iterate from last to zero index for (let i = arr.length - 1; i >= 0; i--) { // If target found return and exit program if (arr[i] === target) { console.log( "The Last index of " + target + " is: " + i ); return ; } } // If not found display output console.log(target + " is not present in the given" ); |
Output
The Last index of 5 is: 6
JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted Array
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.