当前位置:网站首页>Quick sort

Quick sort

2022-06-12 09:07:00 Record dada I

Concept : Set a benchmark for each sorting , Place the number less than the reference point to the left of the reference point , The number greater than the reference point is placed to the right of the reference point , Make the exchange distance larger .

#include<stdio.h>

int a[100];// Global variables 
int n;// Number of numbers to read 
void quicksort(int left,int right) {
    
	int i,j,t,temp;
	if(left>right) {
    
		return;
	}
	temp=a[left];// Benchmark number 
	i=left;
	j=right;
	while(i!=j) {
    
		// Look from right to left 
		while(a[j]>=temp&&i<j) {
    
			j--;
		}
		// Look from left to right 
		while(a[i]<=temp&&i<j) {
    
			i++;
		}
		if(i<j) {
     // If not, change the position 
		temp=a[i];
		a[i]=a[j];
		a[j]=temp; 
		}
	}
	// The first position, i.e. the reference position, is interchanged with the middle position ( The last exchange of every search ). 
	a[left]=a[i];
	a[i]=temp;
	// Recursively handle left and right  
	quicksort(left,i-1);
	quicksort(i+1,right);
	return;
}
int main() {
    
	
	scanf("%d",&n);
	for(int i=1; i<=n; i++) {
    
		scanf("%d",&a[i]);
	}
	
	quicksort(1,n);
	for(int i = 1;i<=n;i++)
	{
    
		printf("%d ",a[i]);
	 } 
	 return 0;
}
原网站

版权声明
本文为[Record dada I]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010531527349.html