C language Fast sorting algorithm sample code sharing _c language

Source: Internet
Author: User
Tags array length benchmark


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]);
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.