465,720 views
32 votes
32 votes
Given a sorted list of integers, output the middle integer. a negative number indicates the end of the input (the negative number is not a part of the sorted list). assume the number of integers is always odd.

ex: if the input is: 2 3 4 8 11 -1
the output is:
middle item: 4
the maximum number of inputs for any test case should not exceed 9. if exceeded, output "too many numbers". hint: first read the data into a vector. then, based on the number of items, find the middle item. 276452.1593070
(must include vector library to use vectors)

User Troyfolger
by
2.4k points

2 Answers

21 votes
21 votes

inputs=[]

num_inputs=int(input())

if(num_inputs>9):

print("Too many inputs")

else:

print(num_inputs)

for i in range(num_inputs):

inputs.append(input())

print(inputs)

middle_position=int(num_inputs/2)

print(inputs[middle_position])

User Basso
by
3.1k points
14 votes
14 votes

Here is a concise C++ code snippet that utilizes vectors to find the middle integer from a sorted list of integers:

The Program

#include <iostream>

#include <vector>

int main() {

std::vector<int> sortedList;

int num;

// Read input into a vector

while (std::cin >> num && num >= 0) {

if (sortedList.size() >= 9) {

std::cout << "too many numbers\\";

return 0;

}

sortedList.push_back(num);

}

// Calculate and output the middle integer

int middleIndex = sortedList.size() / 2;

std::cout << "middle item: " << sortedList[middleIndex] << std::endl;

return 0;

}

User Mohanraj
by
3.0k points