Use the code to generate qsort function to realize bubble sorting

Author's homepage: paper jie's blog_CSDN blog - C language, algorithm detailed field blogger

Author of this article: Hello everyone, I am paper jie, thank you for reading this article, welcome to build three companies.

This article is included in the "C Language" column, which is carefully crafted for college students and programming beginners. The author spends a lot of money (time and energy) to build it, and has all the basic knowledge of C language. I hope it can help readers.

Other columns: "System Analysis of C Language", "Detailed Algorithm Explanation", "C Language - Grammar"

Content sharing: In this issue, we will use the qsort function in the C language to implement bubble sorting. Everyone, please move the small bench and sit down.

    -------- Don't need 998, don't want 98, just one button for three times, you can't lose money if you buy three times, you can't be fooled

foreword

In the previous article, we talked about the implementation of simple bubble sorting (if you are not familiar with it, you can review http://t.csdn.cn/OI3hN ), bubble sorting is a simple sorting in various sorts. The core idea is to compare adjacent elements in pairs, each pair must be compared, and the position is exchanged if it meets the requirements, and repeated until there is no element to compare. Next we will learn about the C language library function qsort, which can also implement bubble sorting, and it is much more perfect than what we wrote before, and can be applied to different types.

Implementation of Bubble Sort

The core idea of ​​bubble sorting is to compare adjacent elements in pairs, each pair must be compared, and the positions are exchanged if they meet the requirements, and repeated until there are no elements to compare

Realization of the algorithm idea: Assume that there are n numbers randomly arranged in the array. 1. In the initial state of the array, we set the entire array as the sorting range, and the range is the number whose subscript is 0-n-1. 2. Starting from the number with the subscript 0, compare the adjacent numbers in pairs, and exchange if the previous number is greater than the latter. After the exchange, compare with the next number, and compare until the last number, so that the largest number is sorted to the end. 3. The front is the first sorting, we need to perform n-1 sorting, assuming that the first sorting mark is 0, the number of marks is i, and each time i+1, then each sorting requires the number of pairwise comparisons for n-1-i. 4 After sorting until there are no elements that can be sorted, the sorting is complete.

The following code is our own implementation of bubble sorting. We use i to control its number of trips, and j controls how many groups it exchanges per trip to achieve ascending order. But there is still a big problem here: it can only sort the data of type int, and it will not work if it is replaced by others. Is there anything that can make it work for different types of data? 

#include <stdio.h>
void bubble_sort(int* arr, int sz)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < sz - 1; i++)
	{
		for (j = 0; j < sz - 1 - i; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
}
int main()
{
	int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_sort(arr, sz);
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

qsort function

Definition of qsort function

The qsort function is a function in the C language library. Its function is to sort different data types in descending or ascending order, which is equivalent to bubble sorting. It doesn't matter if you don't know it, we can go to  qsort - C++ Reference (cplusplus.com)  to check the qsort function.

We can find through the document: qsort has 4 parameters, the first parameter is the first address of the array, the second parameter is the element of the array, the third parameter is the size of the element, and the fourth parameter is a function pointer, which is It is used to compare two elements to be sorted, and its return value is the subtraction of the two elements. If >0, the qsort function will exchange the two elements. The function pointed to by this function pointer needs to be designed by the user, because the designer does not know what type you want to sort. The header file that needs to be referenced is stdlib.h.

Use of qsort function

Here we take int arrays and structure arrays as examples:

An example of an integer array:

#include <stdio.h>
#include <stdlib.h>
//整型数组 - 例
int  compar_int(const void* e1, const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

int main()
{
	//数组
	int arr[10] = { 10,9,8,7,6,5,4,3,2,1 };
	//元素个数
	int sz = sizeof(arr) / sizeof(arr[0]);
	//传参
	qsort(arr, sz, sizeof(arr[0]), compar_int);
	//打印
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

An example of an array of structures:

#include <stdio.h>
#include <stdlib.h>
//整型数组 - 例
struct Stu
{
	char name[20];
	int age;
};

int  compar_int(const void* e1, const void* e2)
{
	return ((struct Stu*)e1)->age - ((struct Stu*)e2) -> age;
}

int main()
{
	//数组
	struct Stu s[] = { {"zhngsan",34},{"lishi",25},{"wangwu", 20}};
	//元素个数
	int sz = sizeof(s) / sizeof(s[0]);
	//传参
	qsort(s, sz, sizeof(s[0]), compar_int);
}

Analog implementation of qsort function

Here is an example of an array of int type:

#include <stdio.h>

int compar_int(const void*e1, const *e2)
{
	return *(int*)e1 - *(int*)e2;
}

//交换函数
//通过char类型加上width来跳过元素
//char+width(类型的大小)刚好是一个类型的大小
void swap(char *e1, char *e2, int width)
{
	int i = 0;
	
	for (i = 0; i < width; i++)
	{
		//每一次循环交换一个字节控制的空间的内容
		//循环完width次彻底交换两个元素
		char tmp = *e1;
		*e1 = *e2;
		*e2 = tmp;
		e1++;
		e2++;
	}
}
//模拟函数
void bublle_sort(void* base, int sz, int width, int (*compar)(const void*, const void*))
{
	int i = 0;
	int j = 0;
	for (i = 0; i < sz - 1; i++)
	{
		for (j = 0; j < sz - 1 - i; j++)
		{
			//如果compar函数大于0 就交换
			if (compar((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[10] = { 10,9,8,7,6,5,4,3,2,1 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	//模拟qsort函数
	bublle_sort(arr, sz, sizeof(arr[0]), compar_int);
		for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
	return 0;
}

Summarize

This is the use and simulation of the qsort function. Through use and simulation, we found that the qsort function is very ingenious. We can't help but sigh how long the brains of the people who wrote these codes are, but I believe that as long as we keep learning, there will always be One day we also have the possibility to write this kind of code, let's encourage each other!

Guess you like

Origin blog.csdn.net/paperjie/article/details/131263096