Hi! I'm new to C-programming (Computer Science freshman) and we have this one assignment where we have to use functions to determine if a user-input array is arranged (monotonically non-increasing/non-decreasing) or not. If it's arranged, we have to use another function to perform a binary search to look for a "key" integer in the array. If it's not arranged in any way, we have to use linear search. I got the binary search and linear search down. I think I also got how to determine if it's arranged or not. What I don't understand is how to use them in functions and how to call them out in my main. HELP!
Code:
#include <stdio.h>
#include <conio.h>
int main()
{
//scans for length of array
int n;
scanf("%d", &n);
//gets elements of array
int arr[n];
int i;
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
//gets target/key
int key;
scanf("%d", &key);
//check if the elements are sorted in any order
int option;
option = is_ordered();
//if elements are sorted, use binary search
if(option == 0 || option == 1)
binary_search();
else
linear_search();
//if target/key is found in list, output "FOUND at index i"
//for some 0<=i<n, ouput "NOT FOUND"
return(0);
}
int is_ordered(int arr[], int option)
{
int i;
int n;
for(i=0;i<n;i++)
{
if(arr[i] <= arr[i+1])
option = 0; //non-increasing
else if(arr[i] >= arr[i+1])
option = 1; //non-decreasing
else
option = -1; //no order --> LINEAR SEARCH
}
return (option);
}
int linear_search(int arr[], int n, int key)
{
int i;
for(i=0;i<n;i++)
{
if(key==arr[i])
printf("FOUND at index %d\n", i);
else
printf("Not found\n");
}
return(0);
}
int binary_search(int arr[], int n, int key)
{
int first, last, middle;
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first <= last )
{
if ( arr[middle] < key )
first = middle + 1;
else if ( arr[middle] == key )
{
printf("%d found at index %d\n", key, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
printf("Not found\n", key);
return 0;
}
This is my code so far. When I compile it, no errors come out. But when I try to run it, it won't work. It only works until the part where I enter the "key" I need to look for.