快速排序
采用一种分治的方法,通常又称为分治法。思想:将原问题分解为若干个规模更小但结构与原问题相似的子问题。递归地解这些问题,然后将这些子问题的解组合为原问题的解。
快速排序就是先找到一个中间轴(一般从起始位置也就是low开始)将 比该值小的数据放左边,比该值大的数据放到右边
实现过程,就是low、high 类似于指针的走位,比pivot值大的交换到high处,比pivot值小的放到low处
java代码:
public class QSort {
public static void main(String[] args) {
int array[] = {5,7,8,3,2};
showArray(array);
System.out.println("\n排序后");
qsort(array,0,4);
showArray(array);
}
private static void swap(int[] arr,int a,int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
private static void qsort(int[] array,int low,int high) {
int i;
if(low<high)
{
i = partition(array,low,high);
qsort(array,low,i-1);
qsort(array,i+1,high);
}
}
private static int partition(int[] array, int low, int high) {
int pivot = array[low];
while(low<high)
{
while(low<high && array[high]>=pivot)
{
high--;
}
array[low] = array[high];
while(low<high && array[low]<=pivot)
{
low++;
}
array[high] = array[low];
}
array[low] = pivot;
return low;
}
private static void showArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
C代码:
//快速排序
#include<stdio.h>
#include<malloc.h>
void showArray(int a[],int len){
for(int i=0;i<len;i++){
printf("%d ",a[i]);
}
}
//分隔,也就是一次快排
int partition(int* array,int low,int high)
{
int pivot = array[low];
while(low<high)
{
while(low<high && array[high]>=pivot)
{
high--;
}
array[low] = array[high];
while(low<high && array[low]<=pivot)
{
low++;
}
array[high] = array[low];
}
array[low] = pivot;
return low;
}
//一次快排分治,然后递归调用
void qsort(int *array,int low,int high)
{
int i;
if(low<high)
{
i = partition(array,low,high);
qsort(array,low,i-1);
qsort(array,i+1,high);
}
}
int main()
{
int array[5] = {5,7,8,3,2};
int len = sizeof(array)/sizeof(int);
showArray(array,len);
qsort(array,0,4);
printf("\n排序后:\n");
showArray(array,len);
return 0;
}
快排是一种分治的思想:分为了两半,所以最好和平均时间复杂度是O(nlog2N)
最坏情况是O(N^2)