结构体数组借助指针排序

来源:互联网 发布:js 加密算法 编辑:程序博客网 时间:2024/05/22 00:18

题目描述:

Sorting without corrupting data

Write a function that sorts an array of Goods according to their prices without actually changing any object in the array.
This function does this by sorting the addresses of the objects instead of swapping the objects in the array.


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 170303 678 999653 343 325175 744 784545 92 75634 705 682758 600 520773 723 983646 865 440152 301 409261 796 170653 343 325152 301 409646 865 440758 600 52034 705 682545 92 756175 744 784773 723 983303 678 999

解题思路:

其实觉得没必要  用结构体指针数组来对结构体数组进行排序。

不过作业题,刚接触指针,还是很有联系的必要的。

只要明白了一点,就可以做题了:

结构体指针数组里的元素是结构体数组的地址,要获得结构体数组的值,下面举例说明。

struct  p{

int  price;

int weight;

}back[100];

然后我们再定义一个结构体指针数组。

p *addresses[100];

赋值:

for(int i=0;i<100;i++){

addresses[i]= & back[i];//&不能缺

}

让addresses里面的元素指向back里面对应的元素,只要

addresses[i] -> price

就可以访问back[i].price了

代码如下





0 0