Steps are:
1. Select an element from the series, called the "benchmark" (pivot);
2. Reorder the sequence, all elements smaller than the base value placed in front of the datum, all elements than the value of the benchmark is placed behind the benchmark (the same number can be on either side). After the partition exits, the datum is positioned in the middle of the series. This is called a partition (partition) operation.
3. Recursively (recursive) sorts a subsequence smaller than the base value element and a subsequence greater than the datum value element.
At the bottom of recursion, the size of the sequence is 0 or one, which is always sorted. Although it has been recursive, the algorithm always exits, because in each iteration (iteration) It will at least put an element in its final position.
Copy Code code as follows:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RANDOM (i) (rand ()%i)
#define N 9//Set array length
Partition operations
int Partition (int array[], int left, int right)
{
int i,j;
int temp;
j = left-1;
for (i=left; i<=right; i++)
{
if (Array[i] <= array[right])//The value of the last array is the benchmark
{
j + +;
temp = Array[j];
ARRAY[J] = Array[i];
Array[i] = temp;
}
}
Return J;
}
Iterative operations
void Quiksort (int array[], int left, int right)
{
int pivot;
if (left < right)
{
Pivot = Partition (array, left, right);
Quiksort (array, left, pivot-1);
Quiksort (array, pivot+1, right);
}
}
Example
int main ()
{
int i = 0;
int a[n];
Srand ((int) time (0)); Set random number of seeds
For (i=0 i<n; i++)//Sort before
{
A[i] = RANDOM (100);
printf ("%d\t", A[i]);
}
printf ("\ n \ nthe");
Quiksort (A, 0, N-1);
For (i=0 i<n; i++)//after sort
{
printf ("%d\t", A[i]);
}
}