Scala Data structure : Linear Search

object linearsearch extends App {

var arr=Array(1,2,3,4,1,5,7,9)
def search(x:Int):(Int,Int)=
{
var res=0; var index=0
for(i<- 0 to arr.length-1)
{
if(arr(i)==x) // search element 1 by 1
{

res= arr(i);index=i // if find put the values of element and index in variables
}

}

(res,index)

}
var a=search(2) // call linear search function
println(“element ” + a._1 + ” found at index ” + a._2) // print the result of linear search function

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s