Sorting Algorithm Part 1: Bubble Sort, Selection Sort, Quick Sort

Preface: According to the request of friends in the comment area, I have published a sorting content in this issue. There are many other kinds of sorting, such as hash sorting, etc., which I will introduce to you later. I hope you can master each sorting skillfully. , you can’t become a big fat man by eating in one go.

1 Bubble sorting (I will go through the process here and use function calls, because I have mentioned it before, but I won’t go into details and use a little pointer content)

void Bubblesort(int arr[], int sz)
{
	for (int i = 0; i < sz; i++)
	{
		for (int j = 0; j < sz - 1 - i; j++)
		{
			if (arr[j] < arr[j + 1])
			{
				int tmp = arr[j + 1];
				arr[j + 1] = arr[j];
				arr[j] = tmp;
			}
		}
	}
}
void Printarray(int* p, int sz)
{
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", *p);
		p++;
	}
}
int main()
{
	int arr[10] = { 3,5,2,6,0,9,8,1,4,7 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	Bubblesort(arr, sz);
	Printarray(arr, sz);
}

2 Select sort

method:

Step 1: Starting from the first number, choose the largest (or smallest number) and put it first

Step 2: Choose the largest number starting from the second number and place it in the second position.

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
//降序排列
void Choosesort(int arr[], int sz)
{
	int j = 0;
	int max = 0;
	for (int i = 0; i < sz; i++)
	{
		for (j = i; j < sz; j++)
		{
			max = arr[i];
			if (max < arr[j])
			{
				int tmp = 0;
				arr[i] = arr[j];
				arr[j] = max;
			}
		}
	}
}
void Printarray(int* p, int sz)
{
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", *p);
		p++;
	}
}
int main()
{
	int arr[10] = { 3,5,2,6,0,9,8,1,4,7 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	Choosesort(arr, sz);
	Printarray(arr, sz);
}

3 Quick sort (Here I will show you the qsort function definition)

#include<stdlib.h>
void Printarray(int* p, int sz)
{
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", *p);
		p++;
	}
}
int (*Quckilysort)(const void* a,const void* b)
{
	return (*(int*)a - *(int*)b);//这里默认是升序排列
}
int main()
{
	//随便搞个乱序数组,你想怎么设置就怎么设置
	int arr[10] = {9,2,4,5,23,46,53,67,76,75};
	size_t num = sizeof(arr) / sizeof(arr[0]);//数组元素个数
	size_t size = sizeof(arr[0]);//一个元素字节大小
	//这里用到了一个知识点,函数名就是地址,地址就是指针
	qsort(arr, num, size, Quckilysort);
	Printarray(arr, num);
	return 0;
}

Guess you like

Origin blog.csdn.net/2301_79811170/article/details/134300740