Skip to content

Instantly share code, notes, and snippets.

@ckung
Created April 2, 2012 13:15
Show Gist options
  • Save ckung/2283333 to your computer and use it in GitHub Desktop.
Save ckung/2283333 to your computer and use it in GitHub Desktop.
public void sort(int[] values) {
// Check for empty or null array
if (values == null || values.length == 0) {
return;
}
this.numbers = values;
number = values.length;
quicksort(0, number - 1);
}
private void quicksort(int low, int high) {
int i = low, j = high;
int compares = high-low-1;
compareCount=compareCount+compares;
// Get the pivot element from the middle of the list
int pivot = numbers[low + (high - low) / 2];
// int pivot = numbers[high];
// Divide into two lists
// while (compare(i, j, 4)) {
while (i <= j) {
// if (compare(numbers[i], pivot, 3)) {
if (numbers[i] < pivot) {
i++;
}
// else if (compare(numbers[j], pivot, 2)) {
else if (numbers[j] > pivot) {
j--;
}
// If we have found a values in the left list which is larger then
// the pivot element and if we have found a value in the right list
// which is smaller then the pivot element then we exchange the
// values.
// As we are done we can increase i and j
// if (compare(i, j, 4)) {
if (i <= j) {
swap(i, j);
i++;
j--;
}
}
// Recursion
if (low < j)
quicksort(low, j);
if (i < high)
quicksort(i, high);
}
private void swap(int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
public static int[] readNumbersFromFile() throws NumberFormatException,
IOException {
List<Integer> numbers = new ArrayList<Integer>();
FileReader fileReader = new FileReader(
"src/programming/set/two/QuickSort.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
int number = Integer.parseInt(line);
numbers.add(number);
}
bufferedReader.close();
int nums[] = new int[numbers.size()];
for (int i = 0; i < numbers.size(); i++) {
nums[i] = numbers.get(i);
}
return nums;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment