将已排序的数组乱序

引用: http://blog.csdn.net/zzqkillyou/article/details/7388690

 

//Java

import java.util.*;
public class Main
{
    public static int[] shuffle(int[] arr)
    {
    int count = arr.length;
    int[] arr2 = new int[count];
    int randCount = 0;  //统计已抽取的个数
    int position = 0;   //随机到的索引
    int k = 0;        //目标数组的索引
    int runCount = 0; //统计运算次数
    while(randCount<count)
    {
        int range = count - randCount;
        Random rand = new Random();
        position = rand.nextInt(range);

        arr2[k] = arr[position];
        arr[position] = arr[count-randCount-1]; //将原数组最后一个填补到已抽取的位置里
        randCount++;
        k++;
        runCount++;
    }

    System.out.println("runCount = " + runCount);
    return arr2;
    }

    public static void main(String[] args)
    {
    int[] arr = new int[10];
    for(int i=0; i<10; i++)
    {
        arr[i] = i;
        System.out.print(arr[i] + " ");
    }
    System.out.println();

    int[] arr2 = shuffle(arr);
    for(int i=0; i<arr2.length; i++)
        System.out.print(arr2[i] + " ");

    System.out.println("\nend.\n");
    }
}

 

posted @ 2013-03-07 12:02  wouldguan  阅读(1301)  评论(0编辑  收藏  举报