【算法】随机洗牌算法

本文探讨了如何实现随机洗牌算法,适用于洗牌、打散数组和生成数组随机排列等场景。最佳算法是从数组首尾开始,将当前元素与剩余元素中的随机元素进行交换,直至遍历完成。算法的空间复杂度为O(1),时间复杂度为O(n)。文章还提供了C++代码示例,强调了不同随机选择方式的注意点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的: 洗牌后, 每张牌出现在每个位置上的概率是相同的

相同问题:

1.shuffle a deck of cards(洗牌)

2.randomize an array(打散数组)

3.generate a random permutation of array elements(随机排列数组)

 

最佳算法(1和2是完全相同的算法的两种做法):

从头或者从尾遍历数组, 把当前元素和剩余元素中一个随机元素交换。 重复此操作一直到遍历完成。 

  1. Start from the first element. Swap it with a random choose element in the whole array(including itself). Now consider the array is from 1 to N-1. Repeat the proccess until you hit the last element.
  2. Start from the last element. Swap it with a random choosen element in the whole array(including itself). Now consider the array is from 0 to N-2. Repeat the proccess until you hit the first element.

复杂度:

Space: O(1)

Time: O(n)

c++ 代码:

/* 1. start from the first element*/
void shuffle(int card[], int n)
{
    // Initial
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值