"Algorithm design-fast sorting" random fast sorting algorithm

Source: Internet
Author: User

1. Algorithm Flow:



But in order to reduce the algorithm because the initial data may have been partially sorted by size, the complexity of the algorithm turns into O (N2) Random selection method

The complexity of the fast sorting algorithm is reduced by randomly generating (p,r) a number between random_partition and then swapping a[i] with A[r].

Code implementation:

#include <stdio.h>
#include <stdlib.h>
#define DATATYPE INT
void Fastsort (DataType a[], int left, int right);//Quick Sort
int random_partition (DataType a[],int p,int R)
{

int I=rand ()% (r-p+1) +p;
{
int temp=a[i];
A[I]=A[R];
A[r]=a[i];
}
int X=a[r];
int i=p-1;
for (int j=p;j<=r-1;j++)
{
if (a[j]<=x)
{
i=i+1;
{
int temp=a[i];
A[I]=A[J];
A[j]=temp;
}
}
}
{
int temp=a[i+1];
A[I+1]=A[R];
A[r]=temp;
}
return i+1;
}
void Fastsort (DataType a[], int left, int. right)
{
if (left<right)
{
int pivotloc=partition (a,left,right);
Fastsort (a,left,pivotloc-1);
Fastsort (A,pivotloc+1,right);
}
}


DataType Main (void)
{
DataType *a = (DataType *) malloc (sizeof (DataType));
DataType key;
DataType i = 1;
A[0] = 0;
printf ("Please enter the numbers casually, then this program for these numbers from small to large order!" Press # to end \ n ");
while (scanf ("%d", &key) = = 1)
{
A[i] = key;
i++;
}
printf ("The result after sorting is: \ n");
Fastsort (A, 1,i-1);
DataType K;
for (k = 1; k <= i-1; k++)
printf ("%d", a[k]);
return 0;
}


"Algorithm design-fast sorting" random fast sorting algorithm

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.