指针进阶
首先,我们通常利用冒泡法来排序数组中的顺序,而在C语言的库函数中还有一个qsort()函数,此函数的头文件是#include<stdlib.h> 下面我们不妨举一个冒泡法的简单例子,让数组从小到大依次排列:
#include<stdio.h>
void bubbleSort(int arr[], int size) {
int i = 0;
for (i = 0; i < size - 1; i++) {
int j = 0;
for (j = 0; j < size - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void print(int arr[], int size) {
int i = 0;
for (i = 0; i < size-1; i++) {
printf("%d ", arr[i]);
}
printf("%d", arr[size - 1]);
}
int main() {
int a[100];
int n = 0;
int i = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
bubbleSort(a, n);
print(a, n);
return 0;
}
我们利用qsort()函数模拟冒泡法排序:
#include<stdio.h>
#include<stdlib.h>
int int_cmp(const void * p1, const void * p2)
{
return (*(int *)p1 - *(int *)p2);
}
void Swap(char * buf1, char * buf2, int width) {
int i = 0;
for (i = 0; i < width; i++) {
char temp = *buf1;
*buf1 = *buf2;
*buf2 = temp;
buf1++;
buf2++;
}
}
void BubbleSort(void *base, size_t num, size_t width, int(*cmp)(const void *e1, const void * e2)) {
int i = 0;
for (i = 0; i < num-1; i++) {
int j = 0;
for (j = 0; j < num - 1 - i; j++) {
if ((cmp((char *)base + j * width, (char *)base + (j + 1)*width) > 0)) {
Swap((char *)base + j * width, (char *)base + (j + 1)*width, width);
}
}
}
}
int main() {
int arr[5] = { 1 ,8 ,5,6,3 };
int size = sizeof(arr) / sizeof(arr[0]);
BubbleSort(arr, size, sizeof(arr[0]),int_cmp);
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
接下来我们继续看一下qsort()函数的实现,笔者认为这段代码利用结构体知识,还是比较好的一道题目,然后进行qsort()排序,在C语言等课程设计的过程中还有比较频繁出现的,建议收藏。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Stu {
char name[20];
char clazz[10];
int age;
int score;
}student;
int cmpScore(const void* e1, const void* e2) {
return ((struct Stu *)e2)->score - ((struct Stu *)e1)->score;
}
int cmpName(const void* e1, const void* e2) {
return strcmp(((struct Stu*)e1)->name,((struct Stu*)e2)->name);
}
int cmpAge(const void *e1, const void *e2){
return ((struct Stu *)e1)->age - ((struct Stu*)e2)->age;
}
int main() {
student s[3] = { {"张三","网络1911",18,99},{"李四","网络1912",19,82},{"王五","网络1913",18,86} };
int size = sizeof(s) / sizeof(s[0]);
qsort(s, size, sizeof(s[0]), cmpScore);
int i = 0;
for (i = 0; i < 3; i++) {
printf("%s %s %d %d\n", s[i].name, s[i].clazz, s[i].age, s[i].score);
}
return 0;
}
|