专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C语言

用直接插入排序对数组中的元素进行升序降序处理解决方法

发布时间:2011-06-28 16:16:48 文章来源:www.iduyao.cn 采编人员:星星草
用直接插入排序对数组中的元素进行升序降序处理
代码如下

//对数组里的元素进行排序
C/C++ code
#include<stdio.h>
#include<conio.h>
void downsort(int v[],int n);     //降序函数声明 
void downsort_2(int v[],int n);    //降序函数声明 ,多一个参数的形式 
void   upsort(int v[],int n);   //升序函数声明
void upsort_2(int v[],int n);    //升序函数声明,多一个参数的形式 
main() 
{
    int a[8]={46,58,15,45,90,18,10,62};
    int n=8;
//    upsort(a,n);
//  upsort_2(a,n);
//  downsort_2(a,n);
    downsort(a,n);
    _getch();
    return(0);
}
void upsort(int a[],int n)
{
    int i,j,temp;
    for(i=1;i<n;i++)
    {
        temp = a[i];
        for(j=i;j>0 && temp<a[j-1];--j)
        {
            a[j] = a[j-1];
        }
    a[j] = temp;
    }
    printf("数组a[]升序排列后:\n\a");
    for(i=0;i<n;i++)
    {
        printf("a[%d]=%d\n",i,a[i]);
    }
}
void downsort(int a[],int n)
{
    int i,j,temp;
    for(i=1;i<n;i++)
    {
        temp = a[i];
        for(j=i;j>0 && temp>a[j-1];--j)
        {
         a[j-1] = a[j];       /*逻辑有点搞不清啦,这里赋值后a[j-1]的数据会丢失,
能不能把downsort函数写的跟upsort函数一样写的那样短小精悍,
downsort_2多了个变量,效率也低。  */
        }
    }
    printf("数组a[]降序排列后:\n\a");  
    for(i=0;i<n;i++)
    {
        printf("a[%d]=%d\n",i,a[i]);
    }
}
void upsort_2(int a[],int n)
{
    int i,j,temp,big;
    for(i=1;i<n;i++)
    {
        temp = a[i];
        for(j=i;j>0 && temp<a[j-1];--j)
        {
            big = a[j];
            a[j] = a[j-1];
            a[j-1] = big;
        }
    }
    printf("数组a[]升序排列后:\n\a");
    for(i=0;i<n;i++)
    {
        printf("a[%d]=%d\n",i,a[i]);
    }
}
void downsort_2(int a[],int n)
{
    int i,j,temp,small;
    for(i=1;i<n;i++)
    {
        temp = a[i];
        for(j=i;j>0 && temp>a[j-1];--j)
        {
         small = a[j-1];
         a[j-1] = a[j];
         a[j] = small;
        }
    }
    printf("数组a[]降序排列后:\n\a");  
    for(i=0;i<n;i++)
    {
        printf("a[%d]=%d\n",i,a[i]);
    }
}


通过调用函数downsort_2 upsort upsort_2能够实现这个功能,函数downsort_2我怎么也实现不了这个功能,求解!!!谢谢

------解决方案--------------------
C/C++ code

void InsertSort(int array[], int length)//直接插入排序
{
    int i, j;
    int key;//存储将要插入的数据

    printf("InsertSort\n");

    for(i = 1; i < length; i++)
    {
        if(array[i] < array[i - 1])
        {
            key = array[i];
            for(j = i - 1; key < array[j]; j--)
                array[j + 1] = array[j];
            array[j + 1] = key;
        }
    }
}
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: