I am trying to work on writing readable code and reducing the amount of redundant code I write. I find this hard to do especially when it comes to algorithms. So, I wrote a quicksort program to practice.
Is there any way I can improve this? I know in terms of efficiency it could be better (instead of taking the leftmost as the pivot, I could choose a pivot in the middle of the array). However, is there a way I could have declared or initialized things better or could I have used a more efficient method of checking different cases?
package quicksort;
/**
* @date December 4, 2015
*/
public class Quicksort {
// private static int[] intArray = new int[]{4, 8, 1, 6, 3, 7, 2, 5};
private static int[] intArray = new int[]{11,10,9,8,7,6,5,4,3,2,1};
//private final static int[] intArray = new int[]{1,2,3,4,5};
/**
* @purpose This method partitions the array and subarrays based on the current pivot point
* @param pivot
* @param leftPointer
* @param rightPointer
*/
private static void partition(int pivot, int leftPointer, int rightPointer) {
while (leftPointer <= rightPointer) {
if (pivot < intArray[rightPointer]) {
rightPointer--;
} else if (pivot > intArray[rightPointer]) {
intArray[leftPointer] = intArray[rightPointer];
intArray[rightPointer] = pivot;
leftPointer++;
} else if (intArray[leftPointer] > pivot) {
intArray[rightPointer] = intArray[leftPointer];
intArray[leftPointer] = pivot;
rightPointer--;
} else {
leftPointer++;
}
}
for (int x = 0; x <= intArray.length - 1; x++) {
System.out.print(intArray[x] + " ");
}
System.out.println();
}
/**
* @purpose This method recursively runs the partition method for the array and subarrays
* @param pivot
* @param leftPointer
* @param rightPointer
*/
private static void quicksort(int pivot, int leftPointer, int rightPointer) {
while (rightPointer != 0) {
partition(intArray[0], 0, rightPointer);
rightPointer--;
}
while (leftPointer != intArray.length - 1) {
leftPointer++;
partition(intArray[leftPointer], leftPointer, intArray.length - 1);
}
}
/**
* @purpose Runs the Quicksort class
* @param args the command line arguments
*/
public static void main(String[] args) {
int leftPointer = 0;
int rightPointer = intArray.length - 1;
int pivot = intArray[0];
quicksort(pivot, leftPointer, rightPointer);
}
}