快速排序

来源:互联网 发布:网络信息监控 编辑:程序博客网 时间:2024/06/18 04:23

每次都调这个快排代码到死,现在就只想记住代码就行

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int N = 100005;void QuickSort(int arr[],int start,int end){    if(start >= end)        return ;    int low = start;    int high = end;    int key = arr[low];    while(low < high)    {        while(low < high && arr[high] > key){            --high;        }        if(low < high)            arr[low++] = arr[high];        while(low < high && arr[low] < key){            ++low;        }        if(low < high)            arr[high--] = arr[low];    }    arr[low] = key;    QuickSort(arr,start,low - 1);    QuickSort(arr,low + 1,end);}int main(){    int arr[N];    int n;    while(~scanf("%d",&n)){    for(int i = 0;i < n;++i)    {        cin >> arr[i];    }    QuickSort(arr,0,n - 1);    printf("%d",arr[0]);    for(int i = 1;i < n;++i)    {        printf(" %d",arr[i]);    }    cout << endl;    //printf("%d\n",arr[n/2]);    }    return 0;}
#include<stdio.h>int arr[100005]={0};void show(int n){    int i;    for(i=0;i<n;++i)    {        if(0==i) printf("%d",arr[i]);        else printf(" %d",arr[i]);    }    printf("\n");}void swap(int *a,int *b){    int n;    n=*a;    *a=*b;    *b=n;}void quicksort(int arr[],int r,int p){    int i=r;    int j=p+1;    int k=arr[r];    if(i<j){    while(i<j){    while(i<p&&arr[++i]<k);    while(arr[--j]>k);    if(i<j) swap(&arr[i],&arr[j]);    }        swap(&arr[r],&arr[j]);        quicksort(arr,r,j-1);        quicksort(arr,j+1,p);    }}int main(){    int n;    int i,j;    while(~scanf("%d",&n)){    for(i=0;i<n;++i)    {        scanf("%d",&arr[i]);    }    quicksort(arr,0,n-1);    show(n);    }    return 0;}