zoukankan      html  css  js  c++  java
  • 将已排序的数组乱序

    引用: 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");
        }
    }
  • 相关阅读:
    FILE
    基础知识const/typedef/函数指针/回调函数
    strchr
    ftell
    rewind
    fread
    poj 2309BST解题报告
    hdoj 4004The Frog's Games解题报告
    哈理工oj 1353LCM与数对解题报告
    poj 2453An Easy Problem解题报告
  • 原文地址:https://www.cnblogs.com/wouldguan/p/2947780.html
Copyright © 2011-2022 走看看