Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
Main Page
Related Pages
Topics
Namespaces
Data Structures
Files
File List
Globals
EXTERNAL_HEADERS
RSL
examples
manual
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
37
template
<
class
RandomAccessIterator>
38
void
quik_sort
(
RandomAccessIterator
beg,
RandomAccessIterator
end)
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
56
int
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
}
i
#define i
Definition
17.names.cpp:126
v
#define v
Definition
17.names.cpp:138
dist
#define dist
Definition
17.names.cpp:464
RandomAccessIterator
#define RandomAccessIterator
Definition
17.names.cpp:528
j
#define j
Definition
17.names.cpp:127
Vector
std::vector< UserClass, std::allocator< UserClass > > Vector
Definition
23.vector.capacity.cpp:43
end
const int end
Definition
27.stringbuf.virtuals.cpp:447
examples.h
quik_sort
void quik_sort(RandomAccessIterator beg, RandomAccessIterator end)
Definition
nthelem.cpp:38
main
int main()
Definition
nthelem.cpp:56
Generated by
1.9.8