Skip to content

Instantly share code, notes, and snippets.

@vicegd
Last active February 23, 2020 08:03
Show Gist options
  • Save vicegd/0688c0c0ef5a9f335259be2fccf69b17 to your computer and use it in GitHub Desktop.
Save vicegd/0688c0c0ef5a9f335259be2fccf69b17 to your computer and use it in GitHub Desktop.
Sorting algorithm: Quicksort method
public class Quicksort {
public void sort(int[] elements) {
quickSort(elements, 0, elements.length-1);
}
/**
* Gets the position of the median of the three (left, right and
* the element which position is in the center between them, and
* moves the elements to order them
* @param elements Array with numbers to calculate the median of three
* @param left Position of the element on the left
* @param right Position of the element on the right
* @return Position of the median of three
*/
private int median_of_three(int elements[], int left, int right){
int center = (left + right) / 2;
if (elements[left] > elements[center])
Util.interchange(elements, left, center);
if (elements[left] > elements[right])
Util.interchange(elements, left, right);
if (elements[center] > elements[right])
Util.interchange(elements, center, right);
return center;
}
/**
* Interchanges element i and element j
* @param elements Array with numbers
* @param i Position of one element to be interchanged
* @param j Position of the other element
*/
public void interchange(int[] elements, int i, int j) {
int temp = elements[i];
elements[i] = elements[j];
elements[j] = temp;
}
private void quickSort(int elements[], int left, int right){
int i = left;
int j = right - 1;
int pivot;
if (left < right){ //if there is one element it is not necessary
int center = median_of_three(elements, left, right);
//if there are less than or equal to 3 elements, there are just ordered
if ((right - left) >= 3){
pivot = elements[center]; //choose the pivot
interchange(elements, center, right); //hide the pivot
do {
while (elements[i] <= pivot && i < right) i++; //first element > pivot
while (elements[j] >= pivot && j > left) j--; //first element < pivot
if (i < j) interchange(elements, i, j);
} while (i < j); //end while
//we set the position of the pivot
interchange(elements, i, right);
quickSort(elements, left, i-1);
quickSort(elements, i+1, right);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment