gpt4 book ai didi

c - 使用多个排序条件对数组进行排序(快速排序)

转载 作者:太空狗 更新时间:2023-10-29 15:27:05 27 4
gpt4 key购买 nike

我正在尝试找出如何(使用快速排序算法)按 2 个标准对结构数组进行排序。例如说我有一个结构:

struct employee{
char gender[12];
char name[12];
int id;
};

假设我的输入是:

struct employee arr[3]=
{
{"male","Matt",1234},
{"female","Jessica",2345},
{"male","Josh",1235}
};

我想先按性别对元素进行排序,然后按升序对 ID 进行排序。一个例子是让所有男性首先按顺序打印他们的 ID,然后是所有女性。我试图在不使用 qsort 函数的情况下执行此操作,但我一点也不知道如何检查 .这是我的排序功能:

void quicksort(struct employee *arr, int left, int right)
{
int pivot, l, r, temp;
if(left < right)
{
p = left;
l = left;
r = right;
while(l < r)
{

while(arr[l].id <= arr[p].id && l <= right)
l++;
while(arr[r].id > arr[p].id && r >= left)
r--;

if(l < r)
{
temp = arr[l].id;
arr[l].id = arr[r].id;
arr[r].id = temp;
}
}


temp = arr[r].id;
arr[r].id = arr[p].id;
arr[p].id = temp;

quicksort(arr, left, r-1);
quicksort(arr, r+1, right);
}
}

有什么建议吗?我在想我可以使用 strcmp 但我无法弄清楚将它包含在函数中的什么地方。

最佳答案

您当然可以内联比较函数,以及与此相关的交换器。下面的这段代码非常基础,依赖于有效的指针,但你明白了。我还冒昧地削减了您的快速排序,修复了过程中出现的问题(我希望如此)。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// employee record
struct employee
{
char gender[12];
char name[12];
int id;
};

// swap employee records
void swap_employee(struct employee *left, struct employee *right)
{
struct employee tmp = *right;
*right = *left;
*left = tmp;
}

// compare employee records
int compare_employee(const struct employee* left,
const struct employee* right)
{
int gender = strcmp(left->gender, right->gender);
return (gender ? gender : (left->id - right->id));
}

// quicksort for employees
static void quicksort_(struct employee *arr, int left, int right)
{
struct employee p = arr[(left+right)/2]; // as good as any
int l = left, r = right; // movable indicies

while (l <= r)
{
while (compare_employee(arr+l, &p) < 0)
++l;
while (compare_employee(arr+r, &p) > 0)
--r;
if (l <= r)
{
swap_employee(arr+l, arr+r);
++l; --r;
}
}

if (left < r)
quicksort_(arr, left, r);
if (l < right)
quicksort_(arr, l, right);
}

// exposed API
void quicksort(struct employee *arr, int count)
{
if (arr && (count>0))
quicksort_(arr, 0, count-1);
}

/* sample usage */
int main(int argc, char *argv[])
{
struct employee arr[]=
{
{"male","Matt",1234},
{"female","Jessica",2345},
{"male","Josh",1235},
{"female","Betsy",2344},
{"male","Roger",1233}
};

quicksort(arr, sizeof(arr)/sizeof(arr[0]));

for (int i=0;i<sizeof(arr)/sizeof(arr[0]);++i)
printf("%s, %s, %d\n", arr[i].gender,arr[i].name, arr[i].id);

return EXIT_SUCCESS;
}

结果

female, Betsy, 2344
female, Jessica, 2345
male, Roger, 1233
male, Matt, 1234
male, Josh, 1235

关于c - 使用多个排序条件对数组进行排序(快速排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373525/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com