File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ #Run
2+
3+ ` node Search/JumpSearch [1,2,3,4] 3 1 `
4+
5+ Output:
6+
7+ 1 . Success - ` 2 (Index) `
8+ 2 . Failure - ` -1 `
Original file line number Diff line number Diff line change 1+ let arr = process . argv [ 2 ] . replace ( "[" , "" ) ;
2+ arr = arr . replace ( "]" , "" ) ;
3+ arr = arr . split ( "," ) . map ( Number ) ;
4+ const x = Number ( process . argv [ 3 ] ) ;
5+ const n = Number ( process . argv [ 4 ] ) ;
6+ // Finding block size to be jumped
7+ step = Math . sqrt ( n ) ;
8+
9+ // Finding the block where element is
10+ // present (if it is present)
11+ prev = 0 ;
12+ while ( arr [ parseInt ( Math . min ( step , n ) - 1 ) ] < x ) {
13+ prev = step ;
14+ step += Math . sqrt ( n ) ;
15+ if ( prev >= n ) {
16+ console . log ( - 1 ) ;
17+ return ;
18+ }
19+ }
20+
21+ // Doing a linear search for x in
22+ // block beginning with prev.
23+ while ( arr [ parseInt ( prev ) ] < x ) {
24+ prev += 1 ;
25+
26+ // If we reached next block or end
27+ // of array, element is not present.
28+ if ( prev == Math . min ( step , n ) ) {
29+ console . log ( - 1 ) ;
30+ return ;
31+ }
32+ }
33+
34+ // If element is found
35+ if ( arr [ parseInt ( prev ) ] == x ) {
36+ console . log ( prev ) ;
37+ }
You can’t perform that action at this time.
0 commit comments