Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
nthelem.cpp
Go to the documentation of this file.
1
30#include <algorithm> // for swap
31#include <vector> // for vector
32#include <iostream> // for cout, endl
33
34#include <examples.h>
35
36
37template <class RandomAccessIterator>
39{
40 const long dist = long (end - beg);
41
42 // Stop condition for recursion.
43 if (dist > 2) {
44 // Use nth_element to do all the work for quik_sort.
45 std::nth_element (beg, beg + (dist / 2), end);
46
47 // Recursive calls to each remaining unsorted portion.
48 quik_sort (beg, beg + (dist / 2 - 1));
49 quik_sort (beg + (dist / 2 + 1), end);
50 }
51 else if (2 == dist && *(end - 1) < *beg)
52 std::swap (beg, end);
53}
54
55
56int main ()
57{
58 typedef std::vector<int, std::allocator<int> > Vector;
59
60 // Initialize a vector using an array of integers.
61 const Vector::value_type arr[] = { 37, 12, 2, -5, 14, 1, 0, -1, 14, 32 };
62
63 Vector v (arr, arr + sizeof arr / sizeof *arr);
64
65 // Print the initial vector.
66 std::cout << "The unsorted values are: \n ";
67
68 for (Vector::iterator i = v.begin (); i != v.end (); ++i)
69 std::cout << *i << ", ";
70
71 std::cout << "\n\n";
72
73 // Use the new sort algorithm.
74 quik_sort (v.begin (), v.end ());
75
76 // Output the sorted vector.
77 std::cout << "The sorted values are: \n ";
78 for (Vector::iterator j = v.begin (); j != v.end (); ++j)
79 std::cout << *j << ", ";
80
81 std::cout << "\n\n";
82
83 return 0;
84}
#define i
Definition 17.names.cpp:126
#define v
Definition 17.names.cpp:138
#define dist
Definition 17.names.cpp:464
#define RandomAccessIterator
Definition 17.names.cpp:528
#define j
Definition 17.names.cpp:127
std::vector< UserClass, std::allocator< UserClass > > Vector
const int end
void quik_sort(RandomAccessIterator beg, RandomAccessIterator end)
Definition nthelem.cpp:38
int main()
Definition nthelem.cpp:56