开发者

find middle elements from an array

开发者 https://www.devze.com 2023-01-25 08:37 出处:网络
In C++ how can i find the middle \'n\' elements of an array? For example if n=3, and the array is [0,1,5,7,7,8,10,14,20]开发者_运维知识库, the middle is [7,7,8].

In C++ how can i find the middle 'n' elements of an array? For example if n=3, and the array is [0,1,5,7,7,8,10,14,20]开发者_运维知识库, the middle is [7,7,8].

p.s. in my context, n and the elements of array are odd numbers, so i can find the middle. Thanks!


This is quick, not tested but the basic idea...

const int n = 5;

// Get middle index
int arrLength = sizeof(myArray) / sizeof(int);

int middleIndex = (arrLength - 1) / 2;
// Get sides
int side = (n - 1) / 2;

int count = 0;

int myNewArray[n];

for(int i = middleIndex - side; i <= middleIndex + side; i++){
     myNewArray[count++] = myArray[i];
}


int values[] = {0,1,2,3,4,5,6,7,8};
const size_t total(sizeof(values) / sizeof(int));
const size_t needed(3);

vector<int> middle(needed);
std::copy(values + ((total - needed) / 2), 
    values + ((total + needed) / 2), middle.begin());

Have not checked this with all possible boundary conditions. With the sample data I get middle = (3,4,5), as desired.


Well, if you have to pick n numbers, you know there will be size - n unpicked items. As you want to pick numbers in the middle, you want to have as many 'unpicked' number on each side of the array, that is (size - n) / 2.

I won't do your homework, but I hope this will help.


Well, the naive algorithm follows:

  1. Find the middle, which exists because you specified that the length is odd.
  2. Repeatedly pick off one element to the left and one element to the right. You can always do this because you specified that n is odd.

You can also make the following observation:

Note that after you've picked the middle, there are n - 1 elements remaining to pick off. This is an even number and (n - 1)/2 must come from the left of the middle element and (n - 1)/2 must come from the right. The middle element has index (length - 1)/2. Therefore, the lower index of the first element selected is (length - 1)/2 - (n - 1)/2 and the upper index of the last element selected is (length - 1)/2 + (n - 1)/2. Consequently, the indices needed are (length - n)/2 - 1 to (length + n)/2 - 1.

0

精彩评论

暂无评论...
验证码 换一张
取 消