【问题标题】:How to do a simple random sort of values within an array如何在数组中对值进行简单的随机排序
【发布时间】:2011-04-29 18:57:41
【问题描述】:

我需要在一个数组中随机排序这些值。

int [] d = new int[26];  
        d[0]=1;  
        d[1]=5;  
        d[2]=10;  
        d[3]=25;  
        d[4]=50;    
        d[5]=75;  
        d[6]=100;  
        d[7]=200;  
        d[8]=300;  
        d[9]=400;  
        d[10]=500;  
        d[11]=750;  
        d[12]=1000;  
        d[13]=2000;  
        d[14]=3000;  
        d[15]=4000;  
        d[16]=5000;  
        d[17]=7500;  
        d[18]=10000;  
        d[19]=25000;   
        d[20]=50000;  
        d[21]=100000;  
        d[22]=250000;  
        d[23]=500000;  
        d[24]=750000;  
        d[25]=1000000;  

【问题讨论】:

  • 顺便说一句。 sortrandom 本质上是相互矛盾的术语,除非你说的是像 Bogosort 这样的东西。
  • 他的意思很可能是随机播放,而不是排序

标签: arrays sorting random


【解决方案1】:

假设您使用 C++ 编写此代码,您可以使用标准库中的 random_shuffle 函数模板。 http://www.cppreference.com/wiki/algorithm/random_shuffle

【讨论】:

    【解决方案2】:

    如果您想编写自己的函数,只需获取两个随机索引并交换它们的值。将其放入一个循环中,并尽可能多地执行,以使数组得到很好的洗牌(我会说次数等于数组中元素数量的两倍)。

    在伪代码中(因为您没有指明语言)

    NUMBER_OF_SHUFFLES = 2;    
    for(ix = 0; ix < NUMBER_OF_SHUFFLES * myArray.length; ix++)
        index1 = random(myArray.length)
        index2 = random(myArray.length)
        temp = index1
    
        myArray[index1] = myArray[index2]
        myArray[index2] = temp
    

    还有更复杂的方法可以做到这一点。看看这个讨论:An Efficient way of randomizing an array - Shuffle code

    【讨论】:

      【解决方案3】:

      如果是java你可以使用

      Arrays.shuffle(d);
      

      【讨论】:

        猜你喜欢
        • 2016-08-15
        • 2013-01-28
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-10
        • 2011-07-15
        相关资源
        最近更新 更多