快速排序的思想是利用了分治的思想,概念就不写了,主要说几种思想,然后贴上代码
二路快排
思想:对于一个数组,找一个基准值,从后面找出比这个基准值小的第一个数字,从前面找比这个基准值大的数字,然后交换,在上一次的位置继续找,依旧是找会面的比基准值小的下一个,前面的比基准值大的下一个,交换,直到i>=j,这个时候找到基准值应该交换的位置,和数组中的值进行交换,然后对于左半部分和右半部分进行递归
public class QuickSort1 {
public static void main(String[] args) {
int[] a = {-1, 2, 1, 3, 5, 6, 4, 3, 2, 0, 9, 8, 7, 10};
//int[] a = {3, 2, 5, 8, 4, 7, 6, 9};
quickSort(a, 0, a.length - 1);
for (int i : a) {
System.out.print(i + " ");
}
}
private static void quickSort(int[] a, int l, int r) {
if (l >= r) {
return;
}
int p = partition(a, l, r);
quickSort(a, l, p - 1);
quickSort(a, p + 1, r);
}
private static int partition(int[] a, int l, int r) {
int i = l, j = r;
int base = a[l];
while (i < j) {
for (; j > i && a[j] >= base; j--) {
}
for (; i < j && a[i] <= base; i++) {
}
if (i < j) {
swap(a, i, j);
}
}
a[l] = a[i];
a[i] = base;
return i;
}
public static void swap(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
}
基本代码
思想:对于数组,将其分为大于基准值和小于基准值的段,然后遍历数组,分为两种情况,大于基准值和小于基准值做分类讨论
public class QuickSort2 {
public static void main(String[] args) {
int[] a = {-1, 2, 1, 3, 5, 6, 4, 3, 2, 0, 9, 8, 7, 10, 11};
//int[] a = {3, 2, 5, 8, 4, 7, 6, 9};
quickSort(a, 0, a.length - 1);
for (int i : a) {
System.out.print(i + " ");
}
}
private static void quickSort(int[] a, int l, int r) {
if (l >= r) {
return;
}
int p = partition(a, l, r);
quickSort(a, l, p - 1);
quickSort(a, p + 1, r);
}
//a[l]-a[j] a[j+1]-a[i]
private static int partition(int[] a, int l, int r) {
// swap(a, l, (int) Math.random() % (r - l + 1) + l);
int temp = a[l];
int j = l;
for (int i = l + 1; i <= r; i++) {
if (a[i] < temp) {
swap(a, ++j, i);
}
}
swap(a, l, j);
return j;
}
public static void swap(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
}
三路快排,
和上面的情况相同,但是分为了三种情况,做分类讨论
public class QuickSort2 {
public static void main(String[] args) {
int[] a = {-1, 2, 1, 3, 5, 6, 4, 3, 2, 0, 9, 8, 7, 10, 11};
//int[] a = {3, 2, 5, 8, 4, 7, 6, 9};
quickSort(a, 0, a.length - 1);
for (int i : a) {
System.out.print(i + " ");
}
}
private static void quickSort(int[] a, int l, int r) {
if (l >= r) {
return;
}
int p = partition(a, l, r);
quickSort(a, l, p - 1);
quickSort(a, p + 1, r);
}
//a[l]-a[j] a[j+1]-a[i]
private static int partition(int[] a, int l, int r) {
// swap(a, l, (int) Math.random() % (r - l + 1) + l);
int temp = a[l];
int j = l;
for (int i = l + 1; i <= r; i++) {
if (a[i] < temp) {
swap(a, ++j, i);
}
}
swap(a, l, j);
return j;
}
public static void swap(int[] a, int x, int y) {
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}
}
为什么要有random函数,因为在数组近乎有序的情况下,选择快排,有可能分割的两段一段是没有值,另一端有值,这样下去的话,在数学期望值下,随机的复杂度比较小,一般情况下,比较常用的是三路快排