快速排序是对冒泡排序的改进,通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。最坏情况的时间复杂度为O(n2),最好情况时间复杂度为O(nlog2n)。
这是我在网上找的一张图,可以帮助大家更好的理解:
代码是实现如下:
public class QuickSort {
/**
* author www.phpddt.com
*/
public static void main(String[] args) {
int n[] = {1,90,-78,57,3,6,3};
QSort(n,0,n.length-1);
for(int i=0; i System.out.print(n[i]+" ");
}
}
public static void QSort(int arr[],int low,int high){
if(low < high){
int pivot = getMiddle(arr,low,high);
QSort(arr,low,pivot-1);
QSort(arr,pivot+1,high);
}
}
//返回中轴的位置
public static int getMiddle(int[] list, int low, int high) {
int tmp = list[low]; //数组的第一个作为中轴
while (low < high) {
while (low < high && list[high] > tmp) {
high--;
}
list[low] = list[high]; //比中轴小的记录移到低端
while (low < high && list[low] <= tmp) {
low++;
}
list[high] = list[low]; //比中轴大的记录移到高端
}
list[low] = tmp; //中轴记录到尾
return low; //返回中轴的位置
}
这是我在网上找的一张图,可以帮助大家更好的理解:
代码是实现如下:
public class QuickSort {
/**
* author www.phpddt.com
*/
public static void main(String[] args) {
int n[] = {1,90,-78,57,3,6,3};
QSort(n,0,n.length-1);
for(int i=0; i System.out.print(n[i]+" ");
}
}
public static void QSort(int arr[],int low,int high){
if(low < high){
int pivot = getMiddle(arr,low,high);
QSort(arr,low,pivot-1);
QSort(arr,pivot+1,high);
}
}
//返回中轴的位置
public static int getMiddle(int[] list, int low, int high) {
int tmp = list[low]; //数组的第一个作为中轴
while (low < high) {
while (low < high && list[high] > tmp) {
high--;
}
list[low] = list[high]; //比中轴小的记录移到低端
while (low < high && list[low] <= tmp) {
low++;
}
list[high] = list[low]; //比中轴大的记录移到高端
}
list[low] = tmp; //中轴记录到尾
return low; //返回中轴的位置
}
}