简体   繁体   English

根据结构成员对结构的指针数组进行排序-最佳选择?

[英]Sorting an array of pointers to a struct on the basis of a struct member - best possible option?

I have the following struct: 我有以下结构:

typedef struct details clientDetails;
struct details 
{
    int socket;  
    char* port;
    char* IP;
    char* hostName;
    int msgSentCount;
    int msgRecvCount;
    char* status;
    char* bufferMsg;
    char* blockedUser[4];
    int blockedCount;   
};

And I have the following array of pointers to the struct: 我有以下指向该结构的指针数组:

clientDetails* allClients[4];

What would be the best possible way to keep the array sorted by the port number of the struct? 使数组按结构的port号排序的最佳方法是什么?

The implementation required would be as follows: 所需的实现如下:

sortByPort(allClients) -> passes a reference to the array and sorts it so that if I print the values of allClients after this function call, I will have it sorted by the port number. sortByPort(allClients) ->将引用传递给数组并对其进行排序,这样,如果在此函数调用后打印allClients的值, allClientsport号对其进行排序。

The problem is based on which sorting algorithm suits best in your application. 问题基于哪种排序算法最适合您的应用程序。 It could be, quick sort, merge sort, or a simple selection sort. 它可以是快速排序,合并排序或简单选择排序。 As your example the length of the array is just 4, I've made an example with selection sort: 作为您的示例,数组的长度仅为4,我用选择排序制作了一个示例:

clientDetails * sortByPort(clientDetails *pClients, size_t len)
{
   size_t i, k;

   for (i = 0; i < len - 1; ++i) {
      size_t k = i;

      for (j = i + 1; j < len; ++j) {
         if (atoi(pClients[j].port) < atoi(pClients[k].port)) {
            k = j;
         }
      }

      clientDetails *tmp = pClients[k];
      pClients[k] = pClients[i];
      pClients[i] = tmp;
   }

   return pClients;
}

You can use strtol instead of atoi if the port is greater than an int value. 如果端口大于int值,则可以使用strtol代替atoi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM