[C语言] 关于萌新对qsort进行的劣质模仿

首先两个for循环确定趟数和单次趟数

因为不确定排序的是  int,char 还是等等.....

所以把地址强制转换成char*(1字节)的地址然后  j(第几个元素) 乘上siz(我们传参过来的字节大小)就等于我们这个元素的位置的地址(包括这个字节大小)确定了

然后进行判断      如果是>0说明说明前面的那个数大 if条件成立 进入swap函数进行交换 如果<=0 那么 if 条件不成立就不交换

交换的时候地址传过去交换 一个字节一个字节的交换(因为是char类型  1字节);交换完进行下次循环

以下为代码

首先是我们的swap交换函数

void swap(char* a, char* b,int siz) {

	for (int i = 0; i < siz; i++) {
		
		char temp = *a;
		*a = *b;
		*b = temp;
		a++;
		b++;
	}
}

模仿的 qsort 代码 和 main 程序入口

void fast_qsort(void* base, int num, int siz, int(*p)(const void*, const void*)) {

	for (int i = 0; i < num - 1; i++) {

		for (int j = i+1; j < num - 1; j++) {

			if (p((char*)base + i * siz, (char*)base + j* siz)>0) {

				swap((char*)base + i * siz, (char*)base + j * siz,siz);


			}
		}

	}

}



int sss(const void* x, const void* y) {
	return *(int*)x - *(int*)y;
}






int main() {

	int arr[] = { 1,3,5,7,9,2,4,6,8,10 };

	int sz = sizeof(arr) / sizeof(arr[0]);

	fast_qsort(arr, sz, sizeof(arr[0]), sss);




	return 0;
}


                

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中,使用qsort排序函数对链表进行排序需要以下步骤: 1. 定义一个结构体来存储链表节点的值和指向下一个节点的指针。 ``` struct Node { int data; struct Node* next; }; ``` 2. 定义一个数组来存储链表节点的值,将链表中的值复制到数组中。 ``` int arr[n]; struct Node* temp = head; for (int i = 0; i < n; i++) { arr[i] = temp->data; temp = temp->next; } ``` 3. 使用qsort函数对数组进行排序。 ``` qsort(arr, n, sizeof(int), compare); ``` 其中,compare是一个比较函数,用于指定排序的方式。例如: ``` int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } ``` 4. 将排好序的数组中的值复制回链表中。 ``` temp = head; for (int i = 0; i < n; i++) { temp->data = arr[i]; temp = temp->next; } ``` 完整代码如下: ``` #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } void sortList(struct Node* head, int n) { int arr[n]; struct Node* temp = head; for (int i = 0; i < n; i++) { arr[i] = temp->data; temp = temp->next; } qsort(arr, n, sizeof(int), compare); temp = head; for (int i = 0; i < n; i++) { temp->data = arr[i]; temp = temp->next; } } int main() { struct Node* head = (struct Node*)malloc(sizeof(struct Node)); head->data = 3; head->next = (struct Node*)malloc(sizeof(struct Node)); head->next->data = 1; head->next->next = (struct Node*)malloc(sizeof(struct Node)); head->next->next->data = 2; head->next->next->next = NULL; sortList(head, 3); struct Node* temp = head; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值