0

I need to sort these values randomly in an array.

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;  
rlb.usa
  • 14,942
  • 16
  • 80
  • 128
  • Possible duplicate : http://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c – rlb.usa Apr 29 '11 at 18:59
  • btw. `sort` and `random` are, essentially contradictory terms, unless you're talking about something like Bogosort. – aviraldg Apr 29 '11 at 18:59
  • he most probably means shuffle, not sort –  Apr 29 '11 at 19:02

3 Answers3

0

If it's java you may use

Arrays.shuffle(d);
RiaD
  • 46,822
  • 11
  • 79
  • 123
0

Assuming you are writing this in C++ you can use random_shuffle function template from the Standard library. http://www.cppreference.com/wiki/algorithm/random_shuffle

0

If you want to write your own function, simply take two random indices and swap their values. Put that in a loop and do it as many times as think necessary for the array to be well shuffled (I would say a number of times equal to two times the number of elements in the array).

In psudo-code (since you haven't indicated the language)

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

There are more sophisticated ways of doing it as well. Check out this discussion: An Efficient way of randomizing an array - Shuffle code

Community
  • 1
  • 1
Alex Russell
  • 189
  • 1
  • 10