user7047949
user7047949

Reputation:

Quicksort on a file

I want to use my quicksort on a file but nothing is happening. My quiksort work, i have try it with a array ramdomly generated.

typedef double *TABLEAU;


TABLEAU charge_tableau(char *s, int nb_elts) {
    FILE *f = NULL;
    TABLEAU t=malloc(nb_elts*sizeof(double));
    f=fopen("data22", "r");
    int i;
    for(i=0; i<nb_elts; i++)
        fscanf(f,"%lf", t+i);
    fclose(f);
    return t;
}


 void permuter(TABLEAU t, int i, int j){
    int tmp;
    tmp=t[i];
    t[i]=t[j];
    t[j]=tmp;
}


/* quicksort */
int partition(TABLEAU t, int m, int n){
    int pivot, i, j;
    pivot = t[m];
    i = m+1;
    for(j= m+1; j < n; j++){
        if(t[j] <= pivot){
            permuter(t, i, j);
            i++;
        }
    }

    permuter(t, m, i-1);
    return i-1;
}


 void triRapide(TABLEAU t, int nb_elts, int m, int n){
    int indPivot;
    if(m<n){
        indPivot = partition(t, m, n);
        triRapide(t, nb_elts, m, indPivot-1);
        triRapide(t, nb_elts, indPivot+1, n);
    }
 }


int main() {

    TABLEAU t;
    int nb_elts=10, m, n;
    t=charge_tableau("data22", nb_elts);
    triRapide(t, nb_elts,m,n);
    return 0;

}

File is like that :

0.612248 0.052802 0.442505 0.189728 0.750432 0.508627 0.491031 0.762011 0.119391 0.603284 0.394294 0.893904 0.842861 0.966140 0.920210 0.973909 0.489751 0.250233 0.671843 0.657750 0.799485 0.947670 0.492462 0.816764 0.351214 0.852527 0.424567 0.701987 0.287918 0.040396 0.928470 0.800661

The problem is my function TABLEAU charge_tableau(char *s, int nb_elts)

Upvotes: 1

Views: 409

Answers (1)

John Bollinger
John Bollinger

Reputation: 180181

Your initial call to function tri_rapide(), from main(), passes the indeterminate values of uninitialized variables m and n as arguments. It looks like you want this instead:

triRapide(t, nb_elts, 0, nb_elts);

Additionally, your partition() function declares pivot to have type int, but type TABLEAU is an alias for double *. You therefore truncate the value of your pivot element. For your particular data, that will truncate all significant digits in every case, so at each partitioning, all elements other than the pivot will be assigned to the upper partition (which, in your implementation, does not require moving them).

Note, too, that the second parameter of function triRapide() is absolutely useless. You do nothing with it other than pass it on when you recurse.

Upvotes: 2

Related Questions