快速排序(也称为分区交换排序)是一种高效的分而治之排序算法。 可以利用循环或递归来实现该算法。 该算法就地执行排序。 快速排序是一种比较排序,这意味着它可以对定义了“小于”关系的任何类型的项目进行排序。
该算法将数组分为两个较小的子数组。 要将算法分为两个数组,请选择数组中的枢轴或元素。 分区阶段包括对数组重新排序,以使所有值小于枢轴的元素都在枢轴之前,而所有值大于枢轴的元素都在其之后。 在分区阶段之后,枢轴处于其最终位置。 枢轴在逻辑上将原始数组分为两个子数组。 然后,“快速排序”算法通过选择新的枢轴点对子数组进行递归排序,并相应地移动值。 每个元素都将被选作枢轴,并将被放置在正确的位置。
Algorithm Classification
下表包含有关快速排序算法分析的信息。 它根据时间复杂度以及空间复杂度定义了最坏,平均和最佳情况。
Please use the following link for an explanation on Big-O notation and what is good, fair and bad.
Quick Sort In Java
public final class QuickSort {
public void sort(int[] collection) {
if (collection != null) {
quickSort(collection, 0, collection.length-1);
} else {
throw new IllegalArgumentException("Input paramenter for array to sort is null.");
}
}
private void quickSort(int[] collection, int firstPosition, int lastPosition) {
if (firstPosition >= lastPosition) {
return;
} else {
int pivotIndex = partition(collection, firstPosition, lastPosition);
quickSort(collection, firstPosition, pivotIndex-1);
quickSort(collection, pivotIndex+1, lastPosition);
}
}
private int partition(int[] collection, int firstPosition, int lastPosition) {
int pivotIndex = selectPivot(firstPosition, lastPosition);
swap (collection, pivotIndex, lastPosition);
int store = firstPosition;
pivotIndex = lastPosition;
for (int i = firstPosition; i <= lastPosition-1 ; i++) {
if (collection[i] <= collection[pivotIndex]) {
swap (collection, i, store);
store++;
}
}
swap (collection, store, pivotIndex);
pivotIndex = store;
return pivotIndex;
}
private void swap(int[] collection, int x, int y) {
int temp = collection[x];
collection[x] = collection[y];
collection[y] = temp;
}
private int selectPivot(int first, int last) {
return (first+last)/2;
}
}
Sample Code (GitHub)
The details of the Quick Sort class can be viewed here.
The details of the Quick Sort JUnit Test class can be viewed here.
Conclusion
快速排序算法构成较大的一组排序算法的一部分。 通过经验学习是我创建这篇关于Java快速排序算法实现的文章的原因。 我学到了很多关于其他人如何解决其他语言(包括Java中的不同实现)的快速排序算法的知识。
The post Quick Sort Algorithm in Java appeared first on Code2Bits.