Quicksort with double* values

ε祈祈猫儿з 提交于 2020-04-22 04:09:04

问题


I am given a programme in C which implements Quicksort on arrays with int values. I need to convert it into a programme which will implement Quicksort on arrays with double* values. I thought that I just need to change "int" declarations into "double*", but for some reason the programme no longer works when I test arrays with other values than integers.

Can someone please help? I really know almost nothing about programming in C and have no idea how to go on. Here is the "int" programme:

void quicksort(int a[], int n)
{
    if (n <= 1) return;
    int p = a[n/2];
    int b[n], c[n];
    int i, j = 0, k = 0;
    for (i=0; i < n; i++) {
        if (i == n/2) continue;
        if ( a[i] <= p) b[j++] = a[i];
        else            c[k++] = a[i];
    }
    quicksort(b,j);
    quicksort(c,k);
    for (i=0; i<j; i++) a[i] =b[i];
    a[j] = p;
    for (i= 0; i<k; i++) a[j+1+i] =c[i];
}


int main(void) {
    int i;
    /* das Array zum Sortieren */
    int test_array[] = { 5, 2, 7, 9, 6, 4, 3, 8, 1 };
    int N = sizeof(test_array)/sizeof(int);

    quicksort(test_array,  N);

    for(i = 0; i < N; i++)
        printf("%d ", test_array[i]);
    printf("\n");

    return 0;
}

回答1:


When you replace the ints with double pointers, you need to change the comparisons - to compare the pointed to values, not the pointers themselves.




回答2:


void quicksort(double a[], int n) {
    if (n <= 1) return;
    double p = a[n/2];
    double b[n], c[n];
    int i, j = 0, k = 0;
    for (i=0; i < n; i++) {
        if (i == n/2) continue;
        if ( a[i] <= p) b[j++] = a[i];
        else            c[k++] = a[i];
    }
    quicksort(b,j);
    quicksort(c,k);
    for (i=0; i<j; i++) a[i] =b[i];
    a[j] = p;
    for (i= 0; i<k; i++) a[j+1+i] =c[i]; }


int main(void) {
    int i;
    /* das Array zum Sortieren */
    double test_array[] = { 5.1, 2.0, 7.8, 9.5, 6.0, 4.7, 3.6, 8.7, 1.1 };
    int N = sizeof(test_array)/sizeof(double);

    for(i = 0; i < N; i++)
        printf("%f ", test_array[i]);
    printf("\n");


    quicksort(test_array,  N);

    for(i = 0; i < N; i++)
        printf("%f ", test_array[i]);
    printf("\n");

    return 0; }

Works great, just changed some int to double. If you want to learn to code in C, you better get a GOOD book. Pointers are BASIC knowledge in C/C++!! Check this for better infos on quicksort: http://de.wikipedia.org/wiki/Quicksort

mfg



来源:https://stackoverflow.com/questions/19894206/quicksort-with-double-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!