Introduction
1 Quicksort is one of the commonly used sort algorithm.
2 To improve English writing,I am trying to introduct the quicksort algorithm by English.Because of my poor English level,The introduction may be simple and easy.
Theoretical principles
1 Quciksort is a divide and conquer algorithm.As a partition algorithm,There should be a corresponding way of dividing and conquering.
Dividing and dividing:Picking an element as a pivot,Each sort places the pivot to its correct position.(Funcition:partition())
and then you will get two arrays on either side of the pivot.The smaller elements(smaller than x)will be put before the pivot,and the greater elements(greater than pivot) will be put after the pivot).
You will do the same for the two arrays that are generated until each element are in the correct poisition.
One way to do partition():(Refer to the CLRS book)
We start from the leftmost element and keep track of the index of smaller(or equal to)element as i,while traversinf,if we find a smaller element,we swap the current element with a[i1+1].Otherwise,we ignore the current element.
Intuitive steps
Pseudocode
quicksort(arr[],low,high)
{
while(low<high)
{
pi=partition(arr,low,high);
quicksort(arr,low,pi-1);
quicksort(arr,pi+1,high);
}
}
partition(arr[],low,high)
{
int low=i-1;
for(int j=low,j<high-1;j++)
{
if(arr[j]<arr[high])
{
i++;
swap(arr[i],arr[j]);
}
}
swap(arr[i+1],arr[high]);
return i+1;
}
Complete code
#include<iostream>
using namespace std;
void swap(int* a, int* b)//A pointer as a parameter
{
int t = *a;
*a = *b;
*b = t;
}
int Partition(int arr[],int low,int high)
{
int i=low-1;//keep track of the nearest smaller number
for(int j=low;j<=high-1;j++)
{
if(arr[j]<arr[high])
{
i++;
swap(&arr[j],&arr[i]);
}
}
swap(&arr[i+1],&arr[high]);//The pivot will be put in the correct poisition In the last step
return i+1;
}
void quickSort(int arr[],int low,int high)
{
if(low<high)
{
int pivot=Partition(arr,low,high);
quickSort(arr,low,pivot-1);
quickSort(arr,pivot+1,high);
//The left and right sequences are processed recursively
}
}
void printArray(int arr[],int n)//print the result
{
int i;
for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) //!=sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
system("pause");
return 0;
}
Conclusion
See the next article for the advanced version about the quicksort.
We will discuss the complexity and some algorithmic problem that borrows the idea of quicksort.