I'm writing a code in ANSI C, this code has to accomplish a single, easy task:
- sort the array
- search in an array for an element
- return element position if found
- else return -1
I defined my function like this:
int search_sorted(int *array, int dimensione, int elemento) {
int i;
for(i=0;i<dimensione;i++){
//fill the array with random numbers
*(array+i)=((int)(rand()%RANDOM_MAX));
}
sort(array,dimensione);
//this should actually sort the array?
for(i=0;i<dimensione;i++){
printf(" posizione %d\t -\t %d\n",i+1,array[i]);
//print the array...
}
for(i=0;i<dimensione;i++){
if(elemento>array[i]){
return -1;
} else if(array[i] == elemento) {
return ++i;
}
}
return -1;
}
//sorting function
int sort (int *array,int dim){
int i, temp;
for (i=0;i<(dim-1);i++){
if(array[i]>array[i+1]){
temp=array[i+1];
array[i+1]=array[i];
array[i]=temp;
}
}
}
The problem is that the sorting simply won't apply, and I don't see a reason why it won't... I'm 100% sure I'm passing the right elements (no compiling errors nor anything...)
Any idea why it doesn't work, and how to solve this?