Novice understanding of quick sort

Novice's understanding of quick sort

——————————————————————————————
Xiaocaiji will share what I have learned this time. I will try to be as detailed as possible. After all, I Also a rookie.

Quick sort
Quick sort is as fast as its name implies. Compared with bubble sort and bucket sort, quick sort combines the advantages of both. Fast and save memory. Let me explain to you.
Let
me give you a chestnut: 6 1 2 7 9 3 4 5 10 8 First, we use the first number 6 as the reference number (in fact, it is a reference number), and then we will classify the following numbers, we will be smaller than 6 Numbers placed on the right side of 6 and numbers greater than 6 are placed on the left. As follows. 3 1 2 5 4 6 9 7 10 8 (Sorted from right to left, where the positions of 3 and 6 are exchanged) At this time, we will perform the same procedure on the left and right sides respectively until the final benchmark number is not required on both sides Exchanged (functions are needed here). But this is just our thinking.
We face a set of numbers to use an array, this time we can not be opened in the middle but the first 6 will then exchange the first number of the number 6 and the middle exchange position (even number is not the problem);
specific The first ordering process is as follows:
6 1 2 7 9 3 4 5 10 8
6 1 2 5 9 3 4 7 10 8
6 1 2 5 4 3 9 7 10 8
3 1 2 5 4 6 9 7 10 8 Repeat the above operation for both sides of 6. You must think about it yourself. I will provide my code.

#include <stdio.h>
int a[100];//定义全局变量  有因为两个子函数都要用
void quicksort(int left,int right)
{
    
    
	int i,t,j,first;
	first=a[left];
	i=left;
	j=right;
	while(i!=j)//两边的下标不相同是可以进行循环,相当于从搜索到了中间
	{
    
    
		while(a[j]>=a[left] && i<j)//先从右向左寻找 
			j--;
		while(a[i]<=a[left] && i<j)//从左向右寻找
			i++;
		if(i<j)//进行交换
		{
    
    
			t=a[j];
			a[j]=a[i];
			a[i]=t;
		}

	}
	a[left]=a[i];
	a[i]=first;//基准数的位置交换
	quicksort(left,i-1);//左边交换一轮后 左边要长度要‘-1’因为基准数站了一个位子
	quicksort(i+1,right);//右边进行操作
}
int main()
{
    
    
	int i,n;
	printf("请输入数组的长度\n");
	scanf("%d",&n);
	printf("请输入要排序的数字\n");
	for(i=1;i<=n;i++)
	{
    
    
		scanf("%d",&a[i]);
		
	}
	quicksort(1,n);
	for(i=1;i<=n;++i)
	{
    
    
		printf("%d",a[i]);
	}
	getchar();getchar();//这里相当于system("pause");
	return 0;
}

The knowledge used here includes understanding of functions, for loops, character exchange, arrays, array subscripts, and understanding of the program flow. If you have any questions, please ask questions. Also welcome to give me suggestions. Thank you!

Guess you like

Origin blog.csdn.net/m0_52699073/article/details/110357323