算法導論 僱用問題的隨機算法 PERMUTE-BY-SORTING(c語言)

       算法導論中僱傭問題的隨機算法,這個算法的過程是先取一個數組test_array,表示每個應聘者的id。然後取一個隨機數組P,這個數組與test_array等長,隨機數的範圍是在0-n^3(n表示應聘者的個數)。這樣取隨機數是爲了避免優先級的重複,即有很小的可能性取到相同的優先級。取出的隨機數組表示test_array數組成員的優先級,依據此優先級來給test_array排序,這個過程就是PERMUTE-BY-SORTING。

c語言測試源碼如下:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

void random_array(int p[], int length)
{
    srand((unsigned)time(NULL));
    int i=0;
    printf("The sort keys are:");
    for (i=0; i<length; i++)
    {
        p[i] = rand() % (length * length * length);
        printf("%d ", p[i]);
    }
    printf("\n");
}//取隨機數組的元素值

void sort(int array[], int p[], int p_length)
{
    int key=0;
    int key2=0;
    for (int i=1; i< p_length; i++)
    {
        key = p[i];
        key2 =array[i];
        int j = i-1;
        while (j >= 0 && p[j] > key)
        {
            p[j+1] = p[j];
            array[j+1] = array[j];
            j--;
        }
        p[j+1] = key;
        array[j+1] = key2;
    }
}//給隨機數組排序,並按排序結果來排序array數組

int main()
{
    int test_array[] ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int len = sizeof(test_array) / sizeof(int);
    int P[len];

    random_array(P, len);
    sort(test_array, P, len);

    printf("The array after sorting:");
    for (int i=0; i<10; i++)
    {
        printf("%d ", test_array[i]);
    }
    printf("\n");

}

利用這樣的方法,可以產生輸入均勻隨機排列,即把數組test_array的元素值隨機排列,從而獲得一個數組的隨機序列。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章