PROGRAM
file name: a1.scala
import scala.util.control._
object a1
{
def main(args: Array[String])
{
var n=0
println("Enter size of array:")
n=Console.readInt()
var arr=new Array[Int](n)
var ch=1
println("Enter array elements:")
for(i <- 0 to n-1)
arr(i)=Console.readInt()
var temp=0
for(i <- 0 to n-1)
{
for(j <- i+1 to n-1)
{
if(arr(i)>arr(j))
{
temp=arr(i)
arr(i)=arr(j)
arr(j)=temp
}
}
}
while(ch!=0)
{
var flag=binary(arr,n)
if(flag== -1)
println("Number not found")
else
println("Number found at index: "+flag)
println("1. to continue 0. to exit")
ch=Console.readInt()
}
}
def binary(arr:Array[Int],n:Int):Int=
{
println("Sorted array is:")
for(i <- arr)
println(i)
println("Enter number to search")
var s=Console.readInt()
var loop= new Breaks;
var result= -1
var lb=0
var ub=n-1
var mid=(lb+ub)/2
loop.breakable
{
while(lb<=ub)
{
mid=(lb+ub)/2
if(s<arr(mid))
ub=mid-1
else if(s>arr(mid))
lb=mid+1
else
{
result=mid
loop.break;
}
}
}
return result;
}
}
OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ scalac a1.scala
warning: there were four deprecation warnings; re-run with -deprecation for details
one warning found
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ scala a1
Enter size of array:
4
Enter array elements:
1
2
4
3
Sorted array is:
1
2
3
4
Enter number to search
3
Number found at index: 2
1. to continue 0. to exit
0
file name: a1.scala
import scala.util.control._
object a1
{
def main(args: Array[String])
{
var n=0
println("Enter size of array:")
n=Console.readInt()
var arr=new Array[Int](n)
var ch=1
println("Enter array elements:")
for(i <- 0 to n-1)
arr(i)=Console.readInt()
var temp=0
for(i <- 0 to n-1)
{
for(j <- i+1 to n-1)
{
if(arr(i)>arr(j))
{
temp=arr(i)
arr(i)=arr(j)
arr(j)=temp
}
}
}
while(ch!=0)
{
var flag=binary(arr,n)
if(flag== -1)
println("Number not found")
else
println("Number found at index: "+flag)
println("1. to continue 0. to exit")
ch=Console.readInt()
}
}
def binary(arr:Array[Int],n:Int):Int=
{
println("Sorted array is:")
for(i <- arr)
println(i)
println("Enter number to search")
var s=Console.readInt()
var loop= new Breaks;
var result= -1
var lb=0
var ub=n-1
var mid=(lb+ub)/2
loop.breakable
{
while(lb<=ub)
{
mid=(lb+ub)/2
if(s<arr(mid))
ub=mid-1
else if(s>arr(mid))
lb=mid+1
else
{
result=mid
loop.break;
}
}
}
return result;
}
}
OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ scalac a1.scala
warning: there were four deprecation warnings; re-run with -deprecation for details
one warning found
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ scala a1
Enter size of array:
4
Enter array elements:
1
2
4
3
Sorted array is:
1
2
3
4
Enter number to search
3
Number found at index: 2
1. to continue 0. to exit
0
No comments:
Post a Comment