Skip to content

Instantly share code, notes, and snippets.

@mesuvash
Created November 17, 2012 12:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mesuvash/4095565 to your computer and use it in GitHub Desktop.
Save mesuvash/4095565 to your computer and use it in GitHub Desktop.
Partial sort : Top K items
import java.util.Arrays;
import java.util.Collections;
public class PartialSort<T extends Comparable<T>> {
private T[] data;
public PartialSort(T[] lst) {
data = lst;
}
public void printArray(T[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + "\t");
}
System.out.print("\n");
}
private void swap(T[] lst, int p, int q) {
T temp = lst[p];
lst[p] = lst[q];
lst[q] = temp;
}
private void swap(int[] lst, int p, int q) {
int temp = lst[p];
lst[p] = lst[q];
lst[q] = temp;
}
public int partition(T[] lst, int start, int end) {
T x;
x = lst[start];
int i = start;
for (int j = start + 1; j <= end; j++) {
if (lst[j].compareTo(x) > 0) { // compares lst[j] greater than x
i = i + 1;
swap(lst, i, j);
}
}
swap(lst, start, i);
return i;
}
public void quickSort(T[] lst, int start, int end) {
if (start < end) {
int index = partition(lst, start, end);
quickSort(lst, start, index - 1);
quickSort(lst, index + 1, end);
}
}
public T[] partialSortTopK(int k) {
T x;
int index, rank;
int start = 0;
int end = data.length - 1;
while (end > start) {
x = data[start];
index = partition(data, start, end);
rank = index + 1;
if (rank >= k) {
end = index - 1;
} else if ((index - start) > (end - index)) {
quickSort(data, index + 1, end);
end = index - 1;
} else {
quickSort(data, start, index - 1);
start = index + 1;
}
}
return data;
}
public static void main(String[] args) {
int n = 50;
int k = 2;
Double[] data = new Double[n];
for (int i = 0; i < n; i++) {
data[i] = i + 1.0;
}
Collections.shuffle(Arrays.asList(data));
PartialSort<Double> partialSort = new PartialSort<Double>(data);
System.out.print("Original Array: \n");
partialSort.printArray(data);
partialSort.partialSortTopK(k);
System.out.print("Partially sorted Array: \n");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + "\t");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment