c - 结构体数组排序的问题

查看:104
本文介绍了c - 结构体数组排序的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

插入排序,实现int数组没问题。
按照此算法,做结构体数组排序时出现问题。

输出截图

为什么结构体数组排序就不行了?是哪里出了问题呢?望指教,谢谢!

typedef struct ElementType {
    int catFood;
    int javaBeen;
    float ratio;
} ElementType;

void print(ElementType arr[],unsigned int len);
void InsertionSort(ElementType arr[], unsigned int len);
void InsertionSortInt(int arr[], unsigned int len);

int main() {
    int i;
    int intArray[8] = {6,3,5,1,8,7,2,4};
    ElementType test[3] = {{7,2,3.500},{5,3,1.666},{6,3,2.00}};
    for(i = 0;i < 8; i++) {
        printf("intArray[%d] is %d ",i,intArray[i]);
    }
    printf("\n");
    InsertionSortInt(intArray,8);
    for(i = 0;i < 8; i++) {
        printf("intArray[%d] is %d ",i,intArray[i]);
    }
    printf("\n");
    print(test,3);
    InsertionSort(test,3);
    print(test,3);
}

/*结构体数组排序,有问题*/
void InsertionSort(ElementType arr[], unsigned int len)
{
    int j, p;
    ElementType tmp;
    for( p = 1; p < len; p++ ) {
        tmp.ratio = arr[p].ratio;
        j = p - 1;
        for(; j >= 0 && tmp.ratio > arr[j].ratio; j--){
            arr[j+1].javaBeen = arr[j].javaBeen;
            arr[j+1].catFood = arr[j].catFood;
            arr[j+1].ratio = arr[j].ratio;
        }
        arr[j+1].javaBeen = tmp.javaBeen;
        arr[j+1].catFood = tmp.catFood;
        arr[j+1].ratio = tmp.ratio;
    }
}

/*插入排序 没问题*/
void InsertionSortInt(int arr[], unsigned int len)
{
    int j, p;
    int tmp;
    for( p = 1; p < len; p++ ) {
        tmp = arr[p];
        j = p - 1;
        for(; j >= 0 && tmp > arr[j]; j--){
            arr[j+1] = arr[j];
        }
        arr[j+1] = tmp;
    }
}  

void print(ElementType arr[], unsigned int len)
{
    unsigned p;
    for (p = 0; p < len; p++) {
        if(p != len -1){
            printf("[%d]=%d %d %.3f,",p,arr[p].javaBeen,arr[p].catFood,arr[p].ratio);
        }else {
            printf("[%d]=%d %d %.3f\n",p,arr[p].javaBeen,arr[p].catFood,arr[p].ratio);
        }
    }
}

解决方案

你 tmp 只保存了 ratio 域,还得保存其他域才行喔

这篇关于c - 结构体数组排序的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆