Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package de.vogella.algorithms.sort.quicksort;
- public class Quicksort {
- private int[] numbers;
- private int number;
- 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;
- // Get the pivot element from the middle of the list
- int pivot = numbers[low + (high-low)/2];
- // Divide into two lists
- while (i <= j) {
- while (numbers[i] < pivot) {
- i++;
- }
- while (numbers[j] > pivot) {
- j--;
- }
- if (i <= j) {
- exchange(i, j);
- i++;
- j--;
- }
- }
- // Recursion
- if (low < j)
- quicksort(low, j);
- if (i < high)
- quicksort(i, high);
- }
- private void exchange(int i, int j) {
- int temp = numbers[i];
- numbers[i] = numbers[j];
- numbers[j] = temp;
- }
- }
Add Comment
Please, Sign In to add comment