Quick sort is an improvement to bubble sort. Bubble sort can only move once at a time, and quick sort can move the number greater than the axis value to the back of the axis value (ascending order), reducing the number of moves
#include<iostream>
using namespace std;
int oneSort(int a[],int x,int y); //one division function
void qSort(int a[],int,int); //quick sort function
int main( ){
int a[]={3,6,5,9,7,1,8,2,4};
//int a[]={1,2,3,4,5,6,7,8 ,9};
int n=sizeof(a)/sizeof(int);
qSort(a,0,n-1);
for(int i=0;i<n;i++)
cout<<a[i]<< " ";
cout<<endl;
return 0;
}
int oneSort(int a[],int x,int y){
int i=x; //i goes from left to right
int j=y; //j goes from right Go left
int tmp=a[x]; //Use the first number as the axis value and save it to tmp
while(i<j){ //When i<j, loop
while(tmp<a[j] &&i<j) //If the value on the right is greater than the axis value, loop
j--;
if(i< j){
a[i]=a[j]; //At this time tmp>a[j], assign the value of a[j] to a[i], then i++
i++;
}
while(a[i]<tmp&&i<j ) //If the value on the left is smaller than the axis value, loop
i++;
if(i<j){
a[j]=a[i]; //At this time, tmp<a[i], set the value of a[i] Assigned to
//a[j], then j--
j--;
}
}
a[i]=tmp; //The value of the last i, j position is the value tmp where the axis value is located, at this time,
//i The value on the left is smaller than tmp, and the value on the right of i is larger than tmp.
//Complete a division
return i; //Return the position of i, and then recursively divide the left and right sides of i
}
void qSort(int a[], int x,int y){
if(x<y){ int k=oneSort(a,x,y); //Get the axis value of one division, and then recursively divide the left and right sides
of the axis //value qSort(a, x,k-1);
qSort(a,k+1,y);
}
}