Search an element in an array where difference between adjacent elements is 1 | Java program to search an element in an array where difference between all elements is 1 ; x is the element to be searched in arr [ 0. . n - 1 ] ; Traverse the given array starting from leftmost element ; If x is found at index i ; Jump the difference between current array element and x ; Driver program to test above function
import java . io . * ; class GFG { static int search ( int arr [ ] , int n , int x ) { int i = 0 ; while ( i < n ) { if ( arr [ i ] == x ) return i ; i = i + Math . abs ( arr [ i ] - x ) ; } System . out . println ( " number ▁ is ▁ not " + " ▁ present ! " ) ; return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 7 , 6 , 7 , 6 , 5 , 4 , 3 , 2 , 3 , 4 , 3 } ; int n = arr . length ; int x = 3 ; System . out . println ( " Element ▁ " + x + " ▁ is ▁ present ▁ at ▁ index ▁ " + search ( arr , n , 3 ) ) ; } }