/*
快速排序是基于分治模式处理 ,对一个典型子数组a[p...r]排序的分治过程:
1.分解 :
A[p..r] 被划分为两个(可能空)的子数组A[p..q-1]和A[q+1..r],使得
A[p..q-1]<=A[q]<=A[q+1..r]
2.解决:通过递归调用快速排序,对子数组A[p..q-1]和A[q+1..r]排序。
*/
#include <stdio.h>
int partition(int *arr, int low, int high)
{
int pivot = arr[high];
int i = low -1;
int j,tmp;
for(j=low;j<high;++j){
if(arr[j]<pivot){
tmp = arr[++i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = tmp;
printf("%d\n",i+1);
return i+1;
}
void quick_sort(int *arr,int low, int high)
{
if(low<high){
int mid = partition(arr,low,high);
quick_sort(arr,low,mid-1);
quick_sort(arr,mid+1,high);
}
}
int main(int argc,char *argv[])
{
int arr[10] = {1,4,6,2,5,8,7,6,9,5};
quick_sort(arr,0,9);
int i;
for(i=0;i<10;++i)
printf("%d ",arr[i]);
printf("\n");
return 0;
}
快速排序是基于分治模式处理 ,对一个典型子数组a[p...r]排序的分治过程:
1.分解 :
A[p..r] 被划分为两个(可能空)的子数组A[p..q-1]和A[q+1..r],使得
A[p..q-1]<=A[q]<=A[q+1..r]
2.解决:通过递归调用快速排序,对子数组A[p..q-1]和A[q+1..r]排序。
*/
#include <stdio.h>
int partition(int *arr, int low, int high)
{
int pivot = arr[high];
int i = low -1;
int j,tmp;
for(j=low;j<high;++j){
if(arr[j]<pivot){
tmp = arr[++i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = tmp;
printf("%d\n",i+1);
return i+1;
}
void quick_sort(int *arr,int low, int high)
{
if(low<high){
int mid = partition(arr,low,high);
quick_sort(arr,low,mid-1);
quick_sort(arr,mid+1,high);
}
}
int main(int argc,char *argv[])
{
int arr[10] = {1,4,6,2,5,8,7,6,9,5};
quick_sort(arr,0,9);
int i;
for(i=0;i<10;++i)
printf("%d ",arr[i]);
printf("\n");
return 0;
}