首页 > 代码库 > 8642 快速排序

8642 快速排序

快排在面试时候或者笔试时经常遇到,代码就是不会写也要记住思想怎么排。用笔和纸好好画画,最经典的排序。

8642 快速排序

时间限制:1000MS 内存限制:1000K

题型:编程题   语言:无限制

描述用函数实现快速排序,并输出每次分区后排序的结果
Input第一行:键盘输入待排序关键的个数n 第二行:输入n个待排序关键字,用空格分隔数据
Output每行输出每趟排序的结果,数据之间用一个空格分隔

Sample Input    10 5 4 8 0 9 3 2 6 7 1

Sample Output      1 4 2 0 3 5 9 6 7 8

                                 0 1 2 4 3 5 9 6 7 8

                                 0 1 2 4 3 5 9 6 7 8

                                 0 1 2 3 4 5 9 6 7 8

                                 0 1 2 34 5 8 6 7 9

                                0 1 2 3 4 5 7 6 8 9

                                0 1 2 3 4 5 6 7 8 9

Hint

作者 yqm

 


答案:

#include<stdio.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define ElemType int

typedef struct
{
    int *elem;
    int length;
    int listsize;
}SqList;

int InitList_Sq(SqList &L,int m)
{
    L.elem=(ElemType*)malloc(m*sizeof(ElemType));
    if(!L.elem)
        return ERROR;
    L.length=0;
    L.listsize=m;
    return OK;
}

int Load_Sq(SqList &L)
{
    int i;
    if(L.length==0)
      printf("The List is empty!");
    else
    {
        for(i=0;i<L.length;i++)
          printf("%d ",L.elem[i]);
    }
    printf("\n");
    return OK;
}

int Partition(SqList &L,int low,int high)
{
    int m,pivotkey=L.elem[low];
    while(low<high)
    {
    while(low<high&&L.elem[high]>=pivotkey)
         high--;
        {m=L.elem[low];L.elem[low]=L.elem[high];L.elem[high]=m;}
    while(low<high&&L.elem[low]<=pivotkey)
        low++;
        {m=L.elem[low];L.elem[low]=L.elem[high];L.elem[high]=m;}
    }    
    return low;
}
void QSort(SqList &T,int low,int high)
{
 int pivotloc;
    if(low<high)
    {
    pivotloc=Partition(T,low,high);
    Load_Sq(T);
    QSort(T,low,pivotloc-1);
    QSort(T,pivotloc+1,high);
    }
}


int main()
{
    SqList T;
    int m,i;
    ElemType e, x;
   scanf("%d",&m);
    if(InitList_Sq(T,m))  // 判断顺序表是否创建成功
    {

          for(i=0;i<m;i++)
            {
            scanf("%d",&x);
            T.elem[i] = x;
            }
          T.length = m;
            QSort(T,0,m - 1);
   }
}



8642 快速排序