Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Implemented jump search in Scala (#5663)
Browse files Browse the repository at this point in the history
* Implemented jump search in Scala

* Moved ImplementJumpSearch to right directory

---------

Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
  • Loading branch information
pramod-karkhani and anandfresh authored May 3, 2024
1 parent edfcd74 commit 489914e
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
38 changes: 38 additions & 0 deletions ImplementJumpSearch.sc
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
object JumpSearch {

def jumpSearch(arr: Array[Int], x: Int): Int = {
val n = arr.length
val jump = Math.sqrt(n.toDouble).toInt // Calculate optimal jump size

var prev = 0

// Find the block where x should be present
while (arr(Math.min(n - 1, prev)) < x) {
prev += jump
}

// Do a linear search in the current block
var curr = Math.max(0, prev - jump)
while (curr < Math.min(n, prev)) {
if (arr(curr) == x) {
return curr
}
curr += 1
}

// Not found
return -1
}

def main(args: Array[String]): Unit = {
val list = Array(1, 2, 3, 4, 5)
val value = 4
val index = jumpSearch(list, value)

if (index != -1) {
println(s"Element $value found at index: $index")
} else {
println(s"Element $value not found in the list")
}
}
}
38 changes: 38 additions & 0 deletions program/program/implement-jump-search/ImplementJumpSearch.sc
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
object JumpSearch {

def jumpSearch(arr: Array[Int], x: Int): Int = {
val n = arr.length
val jump = Math.sqrt(n.toDouble).toInt // Calculate optimal jump size

var prev = 0

// Find the block where x should be present
while (arr(Math.min(n - 1, prev)) < x) {
prev += jump
}

// Do a linear search in the current block
var curr = Math.max(0, prev - jump)
while (curr < Math.min(n, prev)) {
if (arr(curr) == x) {
return curr
}
curr += 1
}

// Not found
return -1
}

def main(args: Array[String]): Unit = {
val list = Array(1, 2, 3, 4, 5)
val value = 4
val index = jumpSearch(list, value)

if (index != -1) {
println(s"Element $value found at index: $index")
} else {
println(s"Element $value not found in the list")
}
}
}

0 comments on commit 489914e

Please sign in to comment.