前提・実現したいこと
Javaで
”bubble sortを利用し、乱数100個を生成して、それらをソートする”
を10回やって、比較回数をだすことに成功しました。次にやらなくてはいけないのは10個出た比較回数の平均を求めることです。
合計の比較回数/10とおいうことはわかるのですが、どうやって比較回数を合計するのかがわかりません。
比較回数=comparisonであっているのかわかりませんが、正解はbubblesortは4950回です。
このクラスをメインメソッドのあるクラスから呼び出したいです。
java
1import java.util.Random; 2public class random{ 3 public static void main(String[] args){ 4 Random random = new Random(); //Create random object of random class that will 5 //enable input via console 6 int[] a = new int[100]; //crate array which has 100 space 7 8 for(int q=0;q<2;q++){ //repeating this action 10 times 9 System.out.println(); 10 System.out.println("\nOrginal order : "); 11 for(int i=0;i<100;i++) //specify that there is 100 numbers in array 12 { 13 a[i]=random.nextInt(100); //put ransom numbers into array list 14 } 15 for(int i =0; i<a.length;i++){ 16 System.out.print(a[i] + " "); 17 } 18 19 IntBubbleSorter.bubbleSort(a); //Pass the array to the bubbleaort 20 21 System.out.println("Sorted in bubble sort : "); //Show sorted values that are sorted by bubble 22 for(int i=0;i<a.length;i++){ 23 System.out.print(a[i] + " "); 24 } 25 } 26 27} 28
java
1public class IntBubbleSorter 2{ 3 public static void bubbleSort(int[] array) 4 { 5 int lastPos; 6 int index; 7 int temp; 8 int comp = 0; 9 10 for( lastPos = array.length -1; lastPos>=0; lastPos--) 11 { 12 for (index = 0; index<=lastPos -1; index++) 13 { 14 comp ++; 15 if(array[index] > array[index+1]) 16 { 17 temp = array[index]; 18 array[index] = array[index+1]; 19 array[index+1] = temp; 20 } 21 } 22 } System.out.println("\nnumber of comparison in bubble sort: " + comp ); 23 } 24 25 26
回答3件
あなたの回答
tips
プレビュー