Download Picking a random element in an array or any other data structure is

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Bloom filter wikipedia , lookup

Java ConcurrentMap wikipedia , lookup

Array data structure wikipedia , lookup

Transcript
Picking a random element in an array or any other data structure is the easiest way to
select a pivot element.
Since the Quick Sort is a divide-and-conquer algorithm, the pivot element acts as the
starting point upon which the array is divided in to two. This endeavors to achieve the
O(N*logN) efficiency for the algorithm.
As you can see from the Java Progam below, we use a 3-statement function
(getRandom()) and only call it once in the main program to get the pivot element.
--------------------------------------------------------------------------------------------------------package random;
import java.util.Random;
public class RandomQuickSort {
/**
* @param args
*
* This is the main method where the program is executed
*/
public static void main(String[] args) {
// the array with elements to sort
int[] arrayToSort = { 19, 18, 81, 8, 94, 92, 97, 98 };
// initialization
RandomQuickSort randomQuickSort = new RandomQuickSort();
// select pivot element randomly, NB: Its called only once
int pivotElement = randomQuickSort.getRandom(arrayToSort);
// print to screen selected element
System.out.println("Pivot Element" + pivotElement);
}
/**
* This method gets the random element from the array
*/
public int getRandom(int[] array) {
Random generator = new Random();
int random = generator.nextInt(array.length);
return array[random];
}
}
-----------------------------------------------------------------------------------------------------------To run the program, copy the enclosed code and save it as RandomQuickSort.java then
run it as a normal Java Application. Try this at least three times to
clearly see the effectiveness of the random selection.