Easiest method to add a mean output in search and sort code?

Apr 3, 2017 at 2:58am
Tried a couple ways but can't seem to get it to compile. Any recommendations on implementing said function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
 #include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>

using namespace std;
void bubble_sort(vector<int>&);

int main() 
{
// binary Search Variables and vector
int beg, end, mid, item;
string choose = "y";
vector<int> binNums;

//Bubble sort variables and vector
int num, val;
vector<int> bbSort;

//Bubble sort block
cout << "Enter the number of elements : ";
cin >> num;
for (int i = 0; i < num; i++) {
cout << "Enter the element " << i + 1 << ": ";
cin >> val;
bbSort.push_back(val);
}

bubble_sort(bbSort);

cout << "List of sorted elements: " << endl;
for (int i = 0; i < num; i++) {
cout << bbSort[i] << " ";
}
cout << endl;

//Binary search block
binNums = bbSort;
while (choose == "y")
{
cout << "\nEnter Item you want to Search: ";
cin >> item;

beg = 1;
end = num;

mid = (beg + end) / 2;

while (beg <= end && binNums[mid] != item)
{
if (binNums[mid]<item)
beg = mid + 1;
else
end = mid - 1;

mid = (beg + end) / 2;
}

if (binNums[mid] == item)
{
cout << "\nElement found at location : " << mid + 1 << endl;
}
else
{
cout << "Element not found";
}

cout << "Do you want to search for another Item(y OR n)? ";
cin >> choose;
}
return 0;
}

void bubble_sort(vector<int>& a)
{
for (int i = a.size(); i > 0; i--)
{
for (int j = 0, k = 1; k < i; j++, k++)
{
if (a[j] > a[k])
{
int swap = a[j];
a[j] = a[k];
a[k] = swap;
}
}
}
}
Apr 3, 2017 at 4:36am
I suggest you test your code as you write it, from what I does your bubble sort order them correctly? Getting the mean doesn't require order, do you mean median?
Apr 3, 2017 at 11:06am
Hello xero3g,

After putting a comment on "#include <stdafx.h>" the program compiled and ran fine here. The gear icon in the top right of code block. If you are having problems post the output of errors that you get. Also helpful to know what IDE and version you are using.

Hope that helps,

Andy
Apr 3, 2017 at 2:32pm
Currently it compiles fine but I'm trying to add a function which calculates the mean of the user defined/inputted array. I don't need median, the assignment requirement simply asks for the mean to be calculated last.
Apr 3, 2017 at 3:19pm
Hello xero3g,

Before you ask the user to continue or exit call a function passing the vector to that function add up all the numbers in the vector and divide by the vector's size.

Hope that helps,

Andy
Topic archived. No new replies allowed.