קוד:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <conio.h>
#define n 30
int swch=0,cmp=0;
void StraightSelect(int a[],int size)
{
int i,j,temp;
for(i=0;i<size-1;i++)
{
for(j=i+1;j<size;j++)
{
cmp++;
if(a[i]>a[j])
{
swch++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
int bin_search(int a[],int size,int num)
{
int low,high,mid;
low=0;
high=size-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==num)
return mid;
else
if(a[mid]>num)
high=mid-1;
else
low=mid+1;
}
return -1;
}
void main()
{
randomize();
clrscr();
int a[n],ar[n],i,num,x;
//klita
for(i=0;i<n-1;i++)
{
a[i]=random(5000)+1;
ar[i] = a[i];
printf("%5d",a[i]);
}
//kriaa func
printf("\n");
printf("select");
printf("\n");
StraightSelect(a,n);
//hadpasa
for(i=0;i<n;i++)
printf("%5d",a[i]);
printf("\n");
for(i=0;i<n;i++)
a[i] = ar[i];
printf("\n");
printf ("number of compares=%d",cmp);
printf("\n");
printf ("number of switches=%d",swch);
cmp=0; swch=0;
printf("\n");
printf("enter 30 numbers to serch");
scanf("%d",num);
while ((num!=-1) &&(i<n))
{
scanf("%d",num);
//kriaa func
x=bin_search(a,n,num);
//hadpasa
printf("%d",x);
}
getch();
}