




Sponsored
Sponsored
This approach involves pairing each name with its corresponding height, sorting these pairs by height in descending order, and then extracting the sorted names. This makes use of the association between each name and its corresponding height.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(n) for storing the list of tuples.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5typedef struct {
6    char* name;
7    int height;
8} Person;
9
10int comparePersons(const void* a, const void* b) {
11    return ((Person*)b)->height - ((Person*)a)->height;
12}
13
14void sortPeople(char** names, int* heights, int n, char** sortedNames) {
15    Person* people = malloc(n * sizeof(Person));
16    for (int i = 0; i < n; ++i) {
17        people[i].name = names[i];
18        people[i].height = heights[i];
19    }
20    qsort(people, n, sizeof(Person), comparePersons);
21    for (int i = 0; i < n; ++i) {
22        sortedNames[i] = people[i].name;
23    }
24    free(people);
25}Create a struct Person to store the names and heights. Populate an array of Person, then sort it using qsort with a comparison function that sorts in descending order by height. Copy the sorted names back to the sortedNames array.
Rather than pairing names and heights, you can directly sort the indices of the height array. After sorting the indices by descending heights, you can retrieve the names based on this sorted order of heights.
Time Complexity: O(n log n) due to sorting the indices.
Space Complexity: O(n) for auxiliary storage of indices.
1defThe code sorts indices based on the heights using negative heights to direct the sorting to descending order. After sorting, use these indices to create the sorted list of names.