Shuffle array in C

前端 未结 7 1813
执念已碎
执念已碎 2020-11-22 03:15

I\'m looking for a function in ANSI C that would randomize an array just like PHP\'s shuffle() does. Is there such a function or do I have to write it on my own

相关标签:
7条回答
  • 2020-11-22 03:50

    The function you are looking for is already present in the standard C library. Its name is qsort. Random sorting can be implemented as:

    int rand_comparison(const void *a, const void *b)
    {
        (void)a; (void)b;
    
        return rand() % 2 ? +1 : -1;
    }
    
    void shuffle(void *base, size_t nmemb, size_t size)
    {
        qsort(base, nmemb, size, rand_comparison);
    }
    

    The example:

    int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    
    srand(0); /* each permutation has its number here */
    
    shuffle(arr, 10, sizeof(int));
    

    ...and the output is:

    3, 4, 1, 0, 2, 7, 6, 9, 8, 5
    
    0 讨论(0)
提交回复
热议问题