The use of sort function and quick sort in c++

Quick sort:
Quick sort is the most commonly used algorithm in sorting algorithms, and its time complexity is O (nlogn)
code:

#include<iostream>
using namespace std;
int a[101],n;
void quicksort(int left,int right){
    
    
	int temp,t,i,j;
	if(left>right)
		return;
	
	temp=a[left];
	i=left;
	j=right;
	while(i!=j)
	{
    
    
		while(i<j&&a[j]>=temp)
			j--;
		while(i<j&&a[i]<=temp)
			i++;
		t=a[i];
		a[i]=a[j];
		a[j]=t;
	}
	a[left]=a[i];
	a[i]=temp;
	
	quicksort(left,i-1);
	quicksort(i+1,right);
	return;
}  
int main(){
    
    
	cout<<"请输入要排序的数字个数:"<<endl;
	cin>>n;
	cout<<"请依次输入"<<n<<"个数:"<<endl;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>a[i]; 
	 } 
	 quicksort(1,n);
	 cout<<"数字排序后为:"<<endl;
		for(int i=1;i<=n;i++)
	{
    
    
		cout<<a[i]<<" "; 
	 }  
	 
}

operation result:
Insert picture description here

The sort function in c++ uses
1. The sort function is included in the c++ standard library whose header file is #include. The sorting method in the standard library can be called to sort the data, but how the sort function is implemented, we don't need to consider!

2. The template of the sort function has three parameters:

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
(1) The first parameter first: is the starting address of the array to be sorted.

(2) The second parameter last: is the end address (the address of the data after the last data)

(3) The third parameter comp is the sorting method: it can be from ascending or descending order. If the third parameter is not written, the default sorting method is from small to large.

3. Examples

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
    
    
	int a[]={
    
    45,12,34,77,90,11,2,4,5,55};
	sort(a,a+10);
	for(int i=0;i<10;i++)
	cout<<a[i]<<" ";
} 

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112856788