knuth洗牌算法

Modified on: Fri, 24 Jan 2020 10:25:58 +0800 热度: 1,973 度
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void swap(int* a,int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int arr[10];

int main()
{
    srand((unsigned)time(NULL));
    for (int i =0;i<10;i++)
        arr[i]=i;
    
    for (int i =0;i<10;i++)
        printf("%3d",arr[i]);
    putchar(10);
    
    for(int i = 10 - 1;i>=0;i--)
        swap(&arr[i],&arr[rand()%(i+1)]);
    
    for (int i =0;i<10;i++)
        printf("%3d",arr[i]);
    putchar(10);
}

添加新评论