快排思想:先定一个主元,小于主元的都在主元左侧,大于主元的在主元右侧,排序好后
主元左侧在进行同意的划分,右侧也进行同样的划分,采用分治思想
代码示例:
package sort;
public class QuickSort {
public static void main(String[] args) {
int a [] = {4,1,6,3,5,67,6788,1,8788,5};
quickSort(a,0,a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
private static void quickSort(int[] a, int l, int r) {
if(l<r){
int q = Divide(a,l,r);
quickSort(a,l,q-1);
quickSort(a,q+1,r);
}
}
private static int Divide(int[] a, int l, int r) {
int q = a[l];
int temp = 0;
while (l<r){
while (l<r&&a[r]>=q){
r--;
}
temp = a[r];
a[r] = a[l];
a[l] = temp;
while (l<r&&a[l]<=q){
l++;
}
temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return l;
}
}
优化:.
1.采用中值作为主元,可以提高性能
2.当待排序的元素小于等于8个的时候采用插入排序,性能更加好
代码示例:
package sort;
public class QuickSort2 {
public static void main(String[] args) {
int a [] = {4,1,6,3,5,67,6788,1,8788,5};
quickSort(a,0,a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
private static void quickSort(int[] a, int l, int r) {
if(l<r){
if(r-l+1<=8){
Insertion_sort.insertion_sort(a);
}
int q = Divide(a,l,r);
quickSort(a,l,q-1);
quickSort(a,q+1,r);
}
}
private static int Divide(int[] a, int l, int r) {
int mid = (r+l)/2;
int midindex = -1;
if(a[l]<=a[mid]&&a[l]>=a[r]){
midindex = l;
}else if(a[r]<=a[mid]&&a[r]>=a[l]){
midindex = r;
}else {
midindex = mid;
}
int temp2 = a[l];
a[l] = a[midindex];
a[midindex] = temp2;
int q = a[l];
int temp = 0;
while (l<r){
while (l<r&&a[r]>=q){
r--;
}
temp = a[r];
a[r] = a[l];
a[l] = temp;
while (l<r&&a[l]<=q){
l++;
}
temp = a[l];
a[l] = a[r];
a[r] = temp;
}
return l;
}
}