This Java code is testing a randomized algorithm for finding the median element of an array. It generates random arrays of size 100001, takes the maximum of the first 4 elements as an estimate of the median, and compares it to the true median found by sorting the entire array. It repeats this process 100 times, counting how many times the estimated median is greater than or equal to the true median.
This Java code is testing a randomized algorithm for finding the median element of an array. It generates random arrays of size 100001, takes the maximum of the first 4 elements as an estimate of the median, and compares it to the true median found by sorting the entire array. It repeats this process 100 times, counting how many times the estimated median is greater than or equal to the true median.
This Java code is testing a randomized algorithm for finding the median element of an array. It generates random arrays of size 100001, takes the maximum of the first 4 elements as an estimate of the median, and compares it to the true median found by sorting the entire array. It repeats this process 100 times, counting how many times the estimated median is greater than or equal to the true median.
חיפוש איבר המערך הגדול מחציון בשיט רנדומאלית5 שעור
זוגי-ניתן להניח כי מספר איברי המערך אי
import java.util.Arrays; public class MedianRandom { // get and print random array public static int[] randArray(int size){ int [] a = new int[size]; for(int i=0; i<a.length; i++){ a[i] = (int)(Math.random()*a.length*10); } return a; } public static void printArray(int [] arr){ for(int t=0; t<arr.length; t++){ System.out.print(arr[t]+", "); } System.out.println(); } public static int medianSort(int arr[]){ Arrays.sort(arr); return arr[arr.length/2]; } public static int median64(int arr[], int first){ int max = arr[0]; for (int i=0; i<first; i++){ if (max < arr[i]) max=arr[i]; } return max; } public static void main(String[] args) { int a[], med64, med; int count = 0, size = 100001, first = 4; for (int i=0; i<100; i++){ a = randArray(size); // printArray(a); med64 = median64(a, first); med = medianSort(a); // printArray(a); if (med64>=med) count++; // System.out.println("med64="+med64+", med="+med); } System.out.println("count = "+count); } }