|
|
|
|
|
|
|
|
Record 2:
2. Creating Loops
Binary Search
var a:Array=[20,10,5,55,6];
var n=a.length;
for(var i=0;i<n;i++)
{
for(var j=0;j<i;j++)
{
if(a[i]<a[j])
{
var tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
}
trace("after sorting:");
for(var i=0;i<n;i++)
{
trace(a[i]);
}
var l=0;
var n=a.length,h=n,m=int((l+h)/2),f=0,key=55;
while(l<=m)
{
if(key==a[m])
{
var f=1;
break;
}
else if(key>a[m])
{
l=m+1;
m=int((l+h)/2);
}
else
{
h=m-1;
m=int((l+h)/2);
}
}
trace("given key="+key);
if(f==1)
trace("element found");
else
trace("element not found");
Output
after sorting:
5
6
10
20
55
given key=55
|
|
|
|
|
|
|
|
|
|
|
|
|