初学者只知道怎么得到最大和最小者,但是不知道怎么给各个书排序
为了完成本关任务,你需要掌握: 1.字符串的存储; 2.一维字符数组; 3.字符串处理函数gets,strlen,puts等; 4.数字的ASCII码值; 5.字符串结束标志‘\0’; 6.有序字符串重组的算法。
我可以回答这个问题。
首先,C语言中数组排序有多种方法,最简单的是使用标准库函数qsort(快速排序),以下是示例代码:
#include <stdio.h>
#include <stdlib.h>
//比较函数,根据需要修改
int cmp(const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}
int main ()
{
int arr[] = {10, 2, 6, 8, 1, 6, 87, 12, 68, 44};
int len = sizeof(arr) / sizeof(*arr);
qsort(arr, len, sizeof(int), cmp);
for (int i = 0; i < len; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
这里是一个用快速排序实现的数组排序程序。首先定义了一个cmp
函数,用于比较数字大小。然后,我们使用qsort
函数来对数组进行排序。该函数接受的参数分别是数组的起始地址(arr
),元素个数(len
),元素大小(sizeof(int)
),以及比较函数(cmp
)。最后,我们遍历排序后的数组并将其打印出来。
当然,这只是一种方法。对于大型的数组,甚至可能需要其他高级排序算法(如归并排序或堆排序),并且需要仔细考虑内存分配和性能问题。同时还要注意防止出现缓冲区溢出等错误。
希望这能对你有所帮助!
排序用 qsort 就可以了
定义一个函数作为参数传进去
int cmp(void *a, void *b)
{
return strcmp(((Book *)a)->name, ((Book *)b)->name);
}
主程序
qsort(数组, 数组长度, sizeof(arr[0]), cmp);
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
struct book
{
string book_name;
string book_author;
int ticket_nums;
int click_nums;
int word_nums;
};
void print_book(book bk)
{
cout << bk.book_name << " " << bk.book_author << " " << bk.ticket_nums << " "
<< bk.click_nums << " " << bk.word_nums << endl;
}
struct cmp
{
bool operator()(const book& b1, const book& b2)
{
if (b1.ticket_nums == b2.ticket_nums)
return b1.click_nums > b2.click_nums;
else
return b1.ticket_nums > b2.ticket_nums;
}
};
int main()
{
int n;
cin >> n;
vector<book>b;
for (int i = 0; i < n; i++)
{
book tmp;
cin >> tmp.book_name >> tmp.book_author >> tmp.ticket_nums >> tmp.click_nums >> tmp.word_nums;
b.push_back(tmp);
}
sort(b.begin(), b.end(), cmp());
for (int i = 0; i < n; i++)
{
print_book(b[i]);
}
system("pause");
return 0;
}
演示结果如下:
供参考:
#include <stdio.h>
#include <stdlib.h>
struct book {
char name[60];
char author[20];
int votes;
int hits;
int words;
}b[100];
void input(struct book* pb, int n)
{
int i;
for (i = 0; i < n; i++)
scanf("%s %s %d %d %d", pb[i].name, pb[i].author,
&pb[i].votes, &pb[i].hits, &pb[i].words);
}
void sort(struct book* pb, int n)
{
int i, j;
struct book tmp;
for (i = n - 1; i > 0; i--) {
for (j = 0; j < i; j++) {
if (pb[j].votes < pb[j + 1].votes ||
pb[j].votes == pb[j + 1].votes && pb[j].hits < pb[j + 1].hits)
{
tmp = pb[j]; pb[j] = pb[j + 1]; pb[j + 1] = tmp;
}
}
}
}
void print(struct book* pb, int n)
{
int i;
for (i = 0; i < n; i++)
printf("%s %s %d %d %d\n", pb[i].name, pb[i].author,
pb[i].votes, pb[i].hits, pb[i].words);
}
int main()
{
int n;
scanf("%d", &n);
input(b, n);
sort(b, n);
print(b, n);
return 0;
}