Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
median_search.cpp File Reference

Median search algorithm More...

#include <algorithm>
#include <iostream>
#include <vector>
Include dependency graph for median_search.cpp:
#define MAX_NUM   20
 maximum number of values to sort from
 
template<class X >
void comp (X x, std::vector< int > *s1, std::vector< int > *s2, std::vector< int > *s3)
 
int main ()
 

Detailed Description

Median search algorithm

Warning
This core is erroneous and gives invorrect answers. Tested using cases from here

Function Documentation

◆ comp()

template<class X >
void comp ( x,
std::vector< int > *  s1,
std::vector< int > *  s2,
std::vector< int > *  s3 
)
Todo:
add documentation
18  {
19  if (s1->size() >= x && s1->size() + s2->size() < x) {
20  std::cout << (*s2)[0] << " is the " << x + 1 << "th element from front";
21  } else if (s1->size() > x) {
22  std::sort(s1->begin(), s1->end());
23  std::cout << (*s1)[x] << " is the " << x + 1 << "th element from front";
24  } else if (s1->size() + s2->size() <= x && s3->size() > x) {
25  std::sort(s3->begin(), s3->end());
26  std::cout << (*s3)[x - s1->size() - s2->size()] << " is the " << x + 1
27  << "th element from front";
28  } else {
29  std::cout << x + 1 << " is invalid location";
30  }
31 }
Here is the call graph for this function:

◆ main()

int main ( )

Main function

38  {
39  std::vector<int> v{25, 21, 98, 100, 76, 22, 43, 60, 89, 87};
43 
44  // creates an array of random numbers
45  // for (int i = 0; i < MAX_NUM; i++) {
46  // int r = std::rand() % 1000;
47  // v.push_back(r);
48  // std::cout << r << " ";
49  // }
50  for (int r : v) std::cout << r << " ";
51 
52  int median = std::rand() % 1000; // initialize to a random numnber
53 
54  std::cout << "\nmedian=" << median << std::endl;
55  int avg1, avg2, avg3, sum1 = 0, sum2 = 0, sum3 = 0;
56 
57  for (int i = 0; i < v.size(); i++) { // iterate through all numbers
58  if (v.back() == v[median]) {
59  avg1 = sum1 + v.back();
60  s2.push_back(v.back());
61  } else if (v.back() < v[median]) {
62  avg2 = sum2 + v.back();
63  s1.push_back(v.back());
64  } else {
65  avg3 = sum3 + v.back();
66  s3.push_back(v.back());
67  }
68  v.pop_back();
69  }
70 
71  int x;
72  std::cout << "enter the no. to be searched form begining:- ";
73  std::cin >> x;
74  comp(x - 1, &s1, &s2, &s3);
75 
76  return 0;
77 }
Here is the call graph for this function:
std::vector< int >
std::vector::size
T size(T... args)
std::sort
T sort(T... args)
std::vector::push_back
T push_back(T... args)
std::cout
comp
void comp(X x, std::vector< int > *s1, std::vector< int > *s2, std::vector< int > *s3)
Definition: median_search.cpp:17
std::rand
T rand(T... args)
std::endl
T endl(T... args)
std::vector::begin
T begin(T... args)
std::vector::end
T end(T... args)
std::cin