class QuickSortExample {
public void quickSort(arr, low, high) {
if(low < high) {
// Find the pivot index of the lower bound of an array
def pivot = this.partition(arr, low, high)
// Apply Divide and conquer strategy
// to sort the left side and right side of an array
// respective to the pivot position
// Left hand side array
this.quickSort(arr, low, pivot - 1)
// Right hand side array
this.quickSort(arr, pivot + 1, high)
}
}
public int partition(arr, low, high) {
// Pick a lowest bound element as an pivot value
def pivot = arr[low]
def i = low
def j = high
while(i < j) {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
while(arr[i] <= pivot && i < high) {
i++
}
// Decrement the index value of "j"
// till the right most values should be greater than to the pivot value
while(arr[j] > pivot && j > low) {
j--
}
// Interchange the values of present
// in the index i and j of an array only if i is less than j
if(i < j) {
def temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
// Interchange the element in j's poisition to the lower bound of an array
// and place the Pivot element to the j's position
arr[low] = arr[j]
arr[j] = pivot
// Finally return the appropriate index position of the pivot element
return j
}
public void printArray(arr) {
def lastIndex = arr.length - 1
// Loop the item and print each item in the console with white space seperated
for (i in 0..lastIndex) {
def num = arr[i]
print(num + " ")
}
println("")
}
public static void main(String[] args) {
def obj = new QuickSortExample()
def arr = [15, 3, 12, 6, -9, 9, 0].toArray()
print("Before Sorting: ")
obj.printArray(arr)
obj.quickSort(arr, 0, arr.length - 1)
print("After Sorting: ")
obj.printArray(arr)
}
}
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15