template to return the "middle value" of an array

I've written a template to return the middle value of 3 distinct parameters. But now I want to re-write it using arrays. How would I go about doing that? Directly below is what I currently have, it and works fine when finding the middle value.

1
2
3
4
5
6
7
8
9
  template <class T>
    T findmid(T a, T b, T c)
    {   
    if (a>b && a<c || a < b && a>c)
        return a;
    if (b>a && b<c || b < a&& b>c)
        return b;
    return c;
    }

If there is an array, would it look something like this?...if there is an array (as opposed to 3 distinct parameters) it might look something like this, but I would like help to see if this is right:

1
2
3
4
5
6
7
8
9
template <class T>
    T findmid(T *a)
    {
    if (a[i]>a[i] && a[i] < a[i] || a[i]<a[i] && a[i]>a[i])
        return a[i]
    if (a[i]>a[i] && a[i] < a[i] || a[i]<a[i] && a[i]>a[i])
        return a[i];
    return a[i];
    }


Would that find the "middle value" of an array a[i]? I have a grasp on the algorithmic aspect, but I'm having trouble with the execution with arrays. Thanks for any help.
Last edited on
sort the array first and then you can select the middle value (or values if array size is even)
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
void sortdescending (T *a, const int n)
{
	float t;
	for (int i = 0; i < n; i++)
		for (int j = 0; j<n; j++)
			if (a[j] < a[j+1])
			{
				t = a[j];
				a[j] = a[j+1];
				a[j+1] = t;
			}
}


Here I've sorted the array in descending order. What would I do now to extract the middle value in its own template?
Last edited on
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
#include <iostream>
template <typename T>
T findMid(T* a, const size_t n)
{
    for (size_t i = 0; i < n; ++i)
    {
        for (size_t j = i + 1; j < n; ++j)
        {
            if(a[i] < a[j])
            {
                T temp = a[i];
                a[i]  = a[j];
                a[j] = temp;
            }
        }
    }
    if(n%2 == 0){return a[(n/2) - 1];}
    else return a[n/2];

}
int main()
{
    int a[] = {1, 4, 8, 9, 31, 12};
    std::cout << "Middle value " << findMid(a, sizeof(a)/sizeof(a[0])) << "\n";
    std::cout << "Array sorted in descending order \n";
    for (size_t i = 0; i < sizeof(a)/sizeof(a[0]); ++i)std::cout << a[i] << "\n";
    std::cout << "\n";
}
Topic archived. No new replies allowed.