Look up "quicksort".
It fits very naturally into a recursive implementation
and is also a very efficient sorting algorithm.
I've included a link to the Solaris source for quicksort.
It is written in C (rather than C++). It is somewhat
complicated because it optimizes the sorting of
short sequences by switching to an insertion sort.
However, you could implement a simpler version which
ran quicksort all the way to completion.
Using C++ how can I write a recursive function to sort an array?
You're a glutton for punishment eh? Heh-heh. Seriously, you can use a recursive binary search to sort your array.
Here is some code I just snagged from the web (source to follow) concerning a recursive binary search:
/* Given: IntArray Array of integers.
Low The low index of the range of integers to search.
High The top index of the range of integers to search.
Target The integer for which to search.
Task: To do a recursive binary search for Target in the specified
range of IntArray.
Return: In the function name, return the index of where Target was
found or -1 if it was not found.
*/
int BinarySearch(IntArrayType IntArray, int Low, int High, int Target)
{
int Mid, Difference;
if (Low %26gt; High)
return -1;
else
{
Mid = (Low + High) / 2;
Difference = IntArray[Mid] - Target;
if (Difference == 0) // IntArray[Mid] == Target
return Mid;
else if (Difference %26lt; 0) // IntArray[Mid] %26lt; Target
return BinarySearch(IntArray, Mid + 1, High, Target);
else
return BinarySearch(IntArray, Low, Mid - 1, Target);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment