快速排序

#include <stdio.h>

int partition(int A[], int p, int q) {
    int x = A[p];
    int i = p;
    int j;
    for (j=p+1; j<=q; j++) {
        if (A[j]<=x) {
            i++;
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
    }
    int temp = A[p];
    A[p] = A[i];
    A[i] = temp;
    return i;
}

void quickSort(int A[], int L, int R) {
    if (L <= R) {
        int mid = partition(A, L, R);
        quickSort(A, L, mid-1);
        quickSort(A, mid+1, R);
    }
}

int main() {
    int A[5] = {3, 6, 8, 2, 1};
    quickSort(A, 0, 4);
    int i;
    for (i=0; i<5; i++) {
        printf("%d\n", A[i]);
    }
    return 0;
}

  







*************************************************************************************8

#include <stdio.h> int quick_sort(int a[], int low, int high)//一趟排序找出并确定枢轴位置 { int key = 0; a[0]= a[low]; key = a[low]; while (low < high) { while (low < high && a[high] >= key) high--; a[low] = a[high]; while (low < high && a[low] <= key) low++; a[high] = a[low]; } a[low] = a[0]; return low; } void qsort(int a[], int low, int high)//递归进行排序,每次确定每部分的枢轴未知直到该部分只剩下一个元素为止 { int key = 0; if (low < high) { key = quick_sort(a, low, high); qsort(a, low, key-1); qsort(a, key+1, high); } } void Quicksort(int a[]) { qsort(a,1,7); } int main() { int a[8] = {0, 23, 27, 45, 98, 65, 17, 78}; int i = 0; for (i = 1; i < 8; i++) //排序前 printf("%4d", a[i]); printf("\n"); Quicksort(a);//调用排序函数 for (i = 1; i < 8; i++) //排序后 printf("%4d", a[i]); printf("\n"); } *********************************************************************************** #include <stdio.h> int quick_sort(int a[], int low, int high)//一趟排序找出并确定枢轴位置 { int key = 0; a[0]= a[low]; key = a[low]; while (low < high) { while (low < high && a[high] >= key) high--; a[low] = a[high]; while (low < high && a[low] <= key) low++; a[high] = a[low]; } a[low] = a[0]; return low; } void qsort(int a[], int low, int high)//递归进行排序,每次确定每部分的枢轴未知直到该部分只剩下一个元素为止 { int key = 0; if (low < high) { key = quick_sort(a, low, high); qsort(a, low, key-1); qsort(a, key+1, high); } } void Quicksort(int a[]) { qsort(a,1,7); } int main() { int a[8] = {0, 23, 27, 45, 98, 65, 17, 78}; int i = 0; for (i = 1; i < 8; i++) //排序前 { printf("%4d", a[i]); } printf("\n\n"); Quicksort(a);//调用排序函数 for (i = 1; i < 8; i++) //排序后 { printf("%4d", a[i]); } printf("\n\n"); }

  

 

*****************************

 

//请问qsort排序怎么写啊?

#include <stdio.h>
#include<stdlib.h>
int comp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int main()
{
int i,n,a[20];

scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
    qsort(a,n,sizeof(int),comp);
    for(i=0;i<n;i++)
    printf("%d\n",a[i]);
    return 0;

}

  

 

 

posted @ 2013-11-19 18:51  博园少主  阅读(122)  评论(0编辑  收藏  举报