直接插入排序===

[实验内容]
1、直接插入排序
2、快速排序
3、堆排序(要求了解原理)
【实验测试数据】
输入数据:{49,38,65,97,76,13,27,49}

 

#include <stdio.h>
#define M 8
typedef struct
{
    int key;
    int other_data;
}RecordType;
void   InsSort(RecordType  r[],  int length);
void QKSort(RecordType r[],int low, int high );
int   QKPass(RecordType r[],int left,int right);
void   InsSort(RecordType  r[],  int length)
{
    int i,j;
    for (i=2;  i<=length;  i++)
    {
        r[0]=r[i];
        j=i-1;
        while (r[0].key< r[j].key )
        {
            r[j+1]= r[j];
            j=j-1;
        }
        r[j+1]=r[0];
    }
}

void QKSort(RecordType r[],int low, int high )
{
    int pos;
    if (low<high)
    {
        pos=QKPass(r, low, high);
        QKSort(r, low, pos-1);
        QKSort(r, pos+1, high);
    }
}

int   QKPass(RecordType r[],int left,int right)
{
    RecordType x;
    int low,high;
    x= r[left];
    low=left;
    high=right;
    while ( low<high )
    {
        while (low< high && r[high].key>=x.key )
            high--;
        if ( low <high )
        {
            r[low]= r[high];
            low++;
        }
        while (low<high && r[low].key<x.key  )
            low++;
        if (  low<high  )
        {
            r[high]= r[low];
            high--;
        }
    }
    r[low]=x;
    return low;
}

int main()
{
    RecordType r[M];
    int i;
    printf("Input the data:");
    for (i=1;i<=M;i++)
        scanf("%d",&(r[i].key));
    InsSort(r,M);
    for (i=1;i<=M;i++)
        printf("%3d",r[i].key);
    printf("\n");
    printf("Input the data:");
    for (i=1;i<=M;i++)
        scanf("%d",&(r[i].key));
    QKSort(r,1,8);
    for (i=1;i<=M;i++)
        printf("%3d",r[i].key);
}


  

posted @ 2013-12-31 11:04  博园少主  阅读(159)  评论(0编辑  收藏  举报