簡體   English   中英

對 1-100 的隨機值數組進行冒泡排序

[英]Bubble Sorting an Array of random values of 1-100

這是作業 1。

現在我必須創建相同的東西,但使用 1-100 個值的隨機數組,我不知道如何將它實現到我已經擁有的東西中。

public class Test {

    public static void main(String a[]) {
    int i;



    int[] array = {9,1,5,8,7,2,1,5,5,6,8,15,3,9,19,18,88,10,1,100,4,8};
    System.out.println("Values Before the sort:\n");
    for (i = 0; i < array.length; i++)
        System.out.print(array[i] + "  ");
    System.out.println();
    bubble_srt(array, array.length);
    System.out.print("Values after the sort:\n");
    for (i = 0; i < array.length; i++)
        System.out.print(array[i] + "  ");
    System.out.println();



}

public static void bubble_srt(int a[], int n) {
    int i, j, t = 0;
    for (i = 0; i < n; i++) {
        for (j = 1; j < (n - i); j++) {
            if (a[j - 1] > a[j]) {
                t = a[j - 1];
                a[j - 1] = a[j];
                a[j] = t;
            }
        }
    }
}

您需要使用隨機生成器來獲取數字。 對於大小為 X 的數組,它將是這樣的:

int[] array = new int[X];
Random random = new Random();

for (int i = 0; i < X; i++)
    array[i] = random.nextInt(100) + 1;

您應該查看Random的文檔。

public void generateRandom()
{
   int[] x = new int[100]; // This initializes an array of length 100
   Random rand = new Random();
   for(int i = 0; i < 100; i++)
   {
       x[i] = rand.nextInt(100); // Use the random class to generate random integers (and give boundaries)
   }
}

我會回應吉姆在評論中所說的話。 足智多謀是軟件開發人員的一項重要技能。 谷歌搜索會很快變成像一個有用的文章這一個

您需要使用Random類來完成此操作。

Random randomGenerator = new Random();
int array = new int[100];
for (int idx = 0; idx < 100; ++idx){
  array[idx] = randomGenerator.nextInt(100) + 1;
}

注意nextInt(int n)方法的使用:

它產生一個介於 0(含)和指定整數(不含)之間的偽隨機整數。 這就是將nextInt(100)的輸出加1的原因,因為它會根據需要將您的輸出范圍從0-991-100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM