summaryrefslogtreecommitdiff
path: root/CPP/cpp_book/chap5/median.cpp
diff options
context:
space:
mode:
authorCarlos Maiolino <[email protected]>2025-09-06 09:37:14 +0200
committerCarlos Maiolino <[email protected]>2025-09-06 09:37:14 +0200
commit2c9056a23e1a55fd21a8e314c903d9325bffd62e (patch)
treea73ba1c7bb60dd89c9e70769dd510e59a49a56a1 /CPP/cpp_book/chap5/median.cpp
parentee8a08bfa24d9a3d09273fdebe8d73ac38c545f9 (diff)
Move CPP code here
Signed-off-by: Carlos Maiolino <[email protected]>
Diffstat (limited to 'CPP/cpp_book/chap5/median.cpp')
-rw-r--r--CPP/cpp_book/chap5/median.cpp21
1 files changed, 21 insertions, 0 deletions
diff --git a/CPP/cpp_book/chap5/median.cpp b/CPP/cpp_book/chap5/median.cpp
new file mode 100644
index 0000000..e9932e8
--- /dev/null
+++ b/CPP/cpp_book/chap5/median.cpp
@@ -0,0 +1,21 @@
+#include <vector>
+#include <algorithm>
+#include <stdexcept>
+
+double median(std::vector<double> vec)
+{
+ std::vector<double>::size_type mid, size;
+
+ size = vec.size();
+
+ if (size == 0)
+ throw std::domain_error("median of an empty vector");
+
+ sort(vec.begin(), vec.end());
+
+ mid = size / 2;
+
+ return size % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2
+ : vec[mid];
+
+}