2

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?

4

1 に答える 1

3

You are trying to implement a bubble sort algorithm. Your implementation is not correct. Your loop just puts the greatest element in the last position.

You need to use another loop which should nest this loop.

for(j=0;j<dim-1;j++)
for (i=0;i<(dim-1-j);i++){
    if(array[i]>array[i+1]){
            temp=array[i+1];
            array[i+1]=array[i];
            array[i]=temp;
    }
于 2012-12-02T14:29:45.213 に答える