10.3 Sort

Write a function that sorts an array of Goods according to their prices without actually changing any object in the array.
This function sorts does this by re-ordering the pointers (addresses) of the objects instead of swapping the objects in the array.
The function has the following header:
void sort(Goods [] goods, int size)*

EXAMPLE INPUT
261 796 170
303 678 999
653 343 325
175 744 784
545 92 756
34 705 682
758 600 520
773 723 983
646 865 440
152 301 409
EXAMPLE OUTPUT
261 796 170
303 678 999
653 343 325
175 744 784
545 92 756
34 705 682
758 600 520
773 723 983
646 865 440
152 301 409

261 796 170
653 343 325
152 301 409
646 865 440
758 600 520
34 705 682
545 92 756
175 744 784
773 723 983
303 678 999
主程序 (不能修改)

#include <stdio.h>

struct Goods
{
    int number;
    int weight;
    int price;
};

void read(struct Goods * goods) {
    scanf("%d %d %d\n", &(*goods).number, 
            &(*goods).weight, &(*goods).price);
}

void readArray(struct Goods goods[], int size) {
    for (int i = 0; i < size; ++ i) {
        read(&goods[i]);
    }
}

void print(const struct Goods * goods) {
    printf("%d %d %d\n", (*goods).number, 
            (*goods).weight, (*goods).price);
}

void printArray(const struct Goods goods[], int size) {
    for (int i = 0; i < size; ++ i) {
        print(&goods[i]);
    }
}

#include "source.c"

void printGoods(const struct Goods * address[], int size) {
    for (int i = 0; i < size; ++ i) {
        print(address[i]);
    }
}

int main() {
    struct Goods goods[10];
    readArray(goods, 10);
    
    const struct Goods * addresses[10];
    for (int i = 0; i < 10; ++ i) {
        addresses[i] = &goods[i];
    }
    sort(addresses, 10);
    
    printArray(goods, 10);
    printf("\n");
    printGoods(addresses, 10);
}

我的答案

#include <stdio.h>
void sort(const struct Goods * addresses[], int size){
    for(int i=0;i<size-1;i++)//充分交换
    {
        for(int j=0;j<size-1;j++)
        {
            if((*addresses[j]).price>(*addresses[j+1]).price)
            {
                const struct Goods * temp;
               temp=addresses[j];
                addresses[j]=addresses[j+1];
                addresses[j+1]=temp;
            }
        }
    }    
}

ZQ的答案

void sort(const struct Goods * addresses[], int size)
{
    const struct Goods * t;
    for(int i=0;i<10-1;i++)
    {
        for(int j=0;j<10-i-1;j++)
        {
            if((*addresses[j]).price>(*addresses[j+1]).price)
            {
                t=addresses[j];
                addresses[j]=addresses[j+1];
                addresses[j+1]=t;
            }
        }
    }

}
上一篇: io.2 下一篇: struct.3
支持 makedown语法