1. Quick Sort
The famous fast-sorting algorithm has a classic partitioning process: We usually take an element as the principal element in some way, and by exchanging it, the element that is smaller than the main element is placed on its left side, and the elements larger than the main element are placed to its right. Given the permutation of n distinct positive integers, how many elements may be selected as the main element before partitioning?
For example, given n = 5, the permutations are 1, 3, 2, 4, 5. The
- There is no element on the left side of 1, the element on the right is larger than it, so it may be the principal element;
- Although 3 of the left element is smaller than it, but its right 2 it is small, so it cannot be the main element;
- Although 2 of the right element is larger than it, but its left 3 is larger than it, so it cannot be the principal element;
- For similar reasons, both 4 and 5 are likely to be the principal elements.
Therefore, there are 3 elements that may be primary.
Input format:
The input gives a positive integer n (<= 105) in line 1th, and the 2nd line is a space-delimited n different positive integer, each of which does not exceed 109.
Output format:
Output the sorted elements sequentially in line 1th
- Input Sample:
101 3 2 4 6 5 7 8 10 9
Sample output:1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
void qsort (int arr[],int left,int right)
{
int i = left;
int j = right;
int mid = (left+right)/2;
int temp = Arr[mid];
while (I<J)
{
for (; i<mid&&arr[i]<=temp; i++); ----------Notice that the loop is over here------
if (I<mid)
{
Arr[mid] = Arr[i];
mid = i;
}
for (; j>mid&&arr[j]>=temp; j--); ----------Notice that the loop is over here------
if (J>mid)
{
Arr[mid] = Arr[j];
MID = J;
}
Arr[mid] = temp;
if (mid-left>1)
{
Qsort (arr,left,mid-1);
}
if (right-mid>1)
{
Qsort (Arr,mid+1,right);
}
}
}
int main ()
{
int i,n;
int arr[10000];
scanf ("%d", &n);
for (i=0; i<n; i++)
{
scanf ("%d", &arr[i]);
}
Qsort (arr,0,n-1);
for (i=0; i<n; i++)
{
printf ("%2d\t", Arr[i]);
}
return 0;
}
9-6 Quick Sort