簡體   English   中英

對文件進行快速排序

[英]Quicksort on a file

我想在文件上使用我的快速排序,但沒有任何反應。 我的quiksort工作,我嘗試用隨機生成的數組進行嘗試。

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;

}

文件是這樣的:

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

問題是我的函數TABLEAU charge_tableau(char * s,int nb_elts)

main()對函數tri_rapide()首次調用將未初始化的變量mn的不確定值作為參數傳遞。 看起來您想要這樣:

triRapide(t, nb_elts, 0, nb_elts);

此外,您的partition()函數聲明pivot類型為int ,但TABLEAU類型是double *的別名。 因此,您將截斷樞軸元素的值。 對於您的特定數據,在每種情況下都會截斷所有有效數字,因此,在每個分區上,除樞軸外的所有元素都將分配給上部分區(在您的實現中,不需要移動它們)。

還要注意,函數triRapide()的第二個參數絕對沒有用。 除了遞歸時將其傳遞外,您什么都不用做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM