I'm trying to do a binarysearch in this piece of code that i have here. if the array has been sorted use a binary search, if it is not sorted use a sequential search. I've manage to get the binarysearch section of the code working, however, no joy with the sequential search.
Can anyone show show me to accomplish this? i'm a newbie to the language, and i'm still learning this stuff. maybe a starting point, then i might be able to figure out the rest of it out myself.
thanks
#include <stdio.h>
#include <ctype.h>//needed for toupper function
#include <time.h>
#include <stdlib.h>
#define SIZE 5
char menuVersion1 ();
void menuVersion2 (char *);
void fill ( int [] , int * );// void fill ( int * );
void print ( int [] );
void sort ( int [] , int * );
int main ()
{
char selection;
int A [SIZE] = {0}; // A is an array of 5 integers
int sorted = 0;
srand ( time (NULL) );
do
{
//selection = menuVersion1 ();
menuVersion2 ( &selection );
switch ( selection )
{
case 'F' : fill (A , &sorted);
break;
case 'P' : print (A);
break;
case 'S' : sort (A, &sorted);
break;
case 'Z' : printf ("Goodbye!\n\n");
break;
case 'Q' : printf ("Query coming up!\n\n");
if ( sorted == 0 ) printf ("the array is not sorted!\n");
else printf ("the array is sorted!\n");
break;
default : printf ("\a\a Invalid selection!!!\n\n");
}
}while ( selection != 'Z');
system ("pause");
return 0;
}
//----------------------------
char menuVersion1 ()
{
char option;
printf ("\n--------\nF-Fill the array \n");
printf ("P-Print the array\n");
printf ("S-Sort the array\n");
printf ("Z-Exit\n");
printf ("Enter your selection :");
scanf(" %c", &option);
return toupper(option);
}
//--------------------------------
void menuVersion2 (char * option)
{
printf ("\n--------\nF-Fill the array \n");
printf ("P-Print the array\n");
printf ("S-Sort the array\n");
printf ("Q-Query the array\n");
printf ("Z-Exit\n");
printf ("Enter your selection :");
scanf(" %c", option);
*option = toupper(*option);
}
//---------------------------------
void fill ( int A [] , int * sorted)
{
int walker;
for (walker = 0 ; walker < SIZE ; walker ++)
{
A[walker] = rand ()%999 + 1;
}
*sorted = 0;
printf ("ARRAY LOADED!!!\n");
}
//----------------------------------------
void print ( int A [])
{
int walker;
printf ("\nHere are the elements ...\n");
for (walker = 0 ; walker < SIZE ; walker ++)
{
printf ("%d\n", A[walker] );
}
printf ("\a ARRAY PRINTED!!!\n");
}
//------------------------
void sort ( int A[] , int * sorted )
{
int i , j , temp ;
*sorted = 1;
for ( j= 0; j<SIZE ; j++)
{
for ( i=0; i<=SIZE-2 ; i++)
{
if ( A[i] > A[i+1])
{
temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
}
}