Created
September 28, 2012 16:44
-
-
Save nitschmann/3800869 to your computer and use it in GitHub Desktop.
JAVA class to sort numeric arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Easy JAVA class to sort numeric arrays | |
* | |
* @author Florian Nitschmann (f.nitschmann@googlemail.com) | |
* @version 0.1 | |
*/ | |
public class QuickSort { | |
/* | |
* void sort - Sort an numeric array | |
* | |
* @access public | |
* @param array int[] - An array with different unsorted numbers | |
* @return null | |
*/ | |
public void sort(int x[]) { | |
this.qSort(x, 0, x.length-1); | |
} | |
/* | |
* void quickSort - Sort the array real due using partition | |
* | |
* @access private | |
* @return null | |
*/ | |
private void qSort(int x[], int left, int right) { | |
if(left < right) { | |
int i = this.partition(x,left,right); | |
this.qSort(x,left,right-1); | |
this.qSort(x,i+1,right); | |
} | |
} | |
/* | |
* int partition - Takes an array in different parts | |
* | |
* @access private | |
* @return int[] | |
*/ | |
private static int partition(int x[], int left, int right) { | |
int pivot, i, j, help; | |
pivot = x[right]; | |
i = left; | |
j = right-1; | |
//Check and change the numbers: | |
while(i <= j) { | |
if(x[i] > pivot) { | |
help = x[i]; | |
x[i] = x[j]; | |
x[j] = help; | |
j--; | |
} | |
else i++; | |
} | |
//Change x[i] and x[right] | |
help = x[i]; | |
x[i] = x[right]; | |
x[right] = help; | |
//Return the new array: | |
return i; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment