programming-examples/java/Searching_Sorting_Algorithms/QuickSelect.java
2019-11-15 12:59:38 +01:00

53 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.jwetherell.algorithms.search;
import java.util.Random;
/**
* In computer science, quickselect is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quicksort sorting algorithm.
* <p>
* Worst-case performance О(n2)<br>
* Best-case performance О(n)<br>
* Average performance O(n)<br>
* <br>
* https://en.wikipedia.org/wiki/Quickselect
*
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public class QuickSelect {
private static final Random RANDOM = new Random();
private static int[] unsorted = null;
private static int[] temp = null;
public static final int find(int value, int[] array) {
unsorted = array;
temp = new int[unsorted.length];
try {
int tempLength = unsorted.length;
int length = tempLength;
int pivot = unsorted[0];
while (length > 0) {
length = tempLength;
pivot = unsorted[RANDOM.nextInt(length)];
tempLength = 0;
for (int i = 0; i < length; i++) {
int iValue = unsorted[i];
if (value == iValue)
return i;
else if (value > pivot && iValue > pivot)
temp[tempLength++] = iValue;
else if (value < pivot && iValue < pivot)
temp[tempLength++] = iValue;
}
unsorted = temp;
length = tempLength;
}
return Integer.MAX_VALUE;
} finally {
QuickSelect.unsorted = null;
QuickSelect.temp = null;
}
}
}