9-6 quick sorting and 9-6 sorting
1. Quick sorting
The famous quick sorting algorithm has a classic division process: we usually use some method to take an element as the principal component, and put the elements smaller than the principal component to its left through the exchange, an element larger than the primary element is placed on the right of the element. Given the arrangement of N distinct positive integers after division, how many elements may be the principal component selected before division?
For example, given N = 5, the values are 1, 3, 2, 4, and 5. Then:
- There is no element on the left of 1, and the element on the right is larger than it, so it may be the principal element;
- Although the element on the left of 3 is smaller than it, the element on the Right of 3 is smaller, so it cannot be the principal element;
- Although the right element of 2 is larger than it, the 3 on the left is larger than it, so it cannot be the principal element;
- For a similar reason, both 4 and 5 may be the principal component.
Therefore, three elements may be the principal element.
Input Format:
The input returns a positive integer N (<= 1st) in row 105. row 2nd is a space-separated N different positive integers. Each number cannot exceed 109.
Output Format:
Output the sorted elements in the first row.
- Input example:
101 3 2 4 6 5 7 8 10 9
Output example: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 ++); // ---------- note that the loop ends here ------
If (I <mid)
{
Arr [mid] = arr [I];
Mid = I;
}
For (; j> mid & arr [j]> = temp; j --); // ---------- the loop ends 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;
}