当前位置: 面试刷题>> 根据身高重排队列 (经典算法题500道)
### 题目描述补充
**题目:根据身高重排队列**
给定一个包含多个人的数组,每个人用一个对象表示,对象中至少包含两个属性:`name`(姓名)和`height`(身高,单位:厘米)。要求编写一个函数,该函数接收这样的数组作为输入,并返回一个新的数组,其中元素按照身高从高到低的顺序重新排列。如果两个人的身高相同,则保持他们在原数组中的相对顺序不变。
### 示例
输入:
```json
[
{"name": "Alice", "height": 165},
{"name": "Bob", "height": 170},
{"name": "Charlie", "height": 165},
{"name": "David", "height": 180}
]
```
输出:
```json
[
{"name": "David", "height": 180},
{"name": "Bob", "height": 170},
{"name": "Alice", "height": 165},
{"name": "Charlie", "height": 165}
]
```
### PHP 示例代码
```php
function sortPeopleByHeight($people) {
usort($people, function($a, $b) {
if ($a['height'] == $b['height']) {
return 0;
}
return ($a['height'] > $b['height']) ? -1 : 1;
});
return $people;
}
// 示例用法
$people = [
["name" => "Alice", "height" => 165],
["name" => "Bob", "height" => 170],
["name" => "Charlie", "height" => 165],
["name" => "David", "height" => 180]
];
$sortedPeople = sortPeopleByHeight($people);
print_r($sortedPeople);
```
### Python 示例代码
```python
def sort_people_by_height(people):
return sorted(people, key=lambda x: x['height'], reverse=True)
# 示例用法
people = [
{"name": "Alice", "height": 165},
{"name": "Bob", "height": 170},
{"name": "Charlie", "height": 165},
{"name": "David", "height": 180}
]
sorted_people = sort_people_by_height(people)
print(sorted_people)
```
### JavaScript 示例代码
```javascript
function sortPeopleByHeight(people) {
return people.sort((a, b) => b.height - a.height);
}
// 示例用法
const people = [
{name: "Alice", height: 165},
{name: "Bob", height: 170},
{name: "Charlie", height: 165},
{name: "David", height: 180}
];
const sortedPeople = sortPeopleByHeight(people);
console.log(sortedPeople);
```
**码小课网站中有更多相关内容分享给大家学习**,涵盖了各种算法和数据结构的知识,适合不同水平的开发者学习和提升。