answersLogoWhite

0


Best Answer

Swapping array elements is simple enough. The only issue is what to do with the middle element when there are an odd number of elements. The following program simply leaves it where it is.

#include<iostream>

#include<vector>

template<typename T>

void exchange (std::vector<T>& v)

{

if (v.size()<2) return;

size_t left = 0;

size_t right = v.size() / 2;

if (v.size()%2)

++right; // skip middle element

while (right < v.size())

std::swap (v[left++], v[right++]);

}

int main()

{

std::vector<unsigned> v {4, 8, 15, 16, 23, 42, 69};

for (auto n : v) std::cout << n << ' '; std::cout << std::endl;

exchange (v);

for (auto n : v) std::cout << n << ' '; std::cout << std::endl;

}

User Avatar

Wiki User

9y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

10y ago

The following is the inefficient way of doing it; physically swapping each individual element in the array (assuming both arrays are of the same size):

template<typename T>

void copy(T& A[], T& B[], size_t size)

{

if( &A == &B )

return;

for(int index=0; index<size; ++index)

{

A[index]^=B[index]^=A[index]^=B[index];

}

}

A more efficient method is to simply point at the two arrays, and swap the pointer values instead. By doing so, you not only save a great deal of processing time (swapping two pointer variable values instead of potentially millions of elements), you also overcome the problem of swapping arrays of different sizes. The trick is to use pointers to the arrays, rather than references to the arrays, since references cannot be swapped, other than by physically swapping the elements being referred to. Also, it pays to use arrays of pointers to objects rather than arrays of objects, regardless of the object complexity. Copying pointers is always more efficient than copying objects.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: How do you write a program in c plus plus to swap each half of an array?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Continue Learning about Engineering

How do you find the quartile in an even array of values?

Divide the array in half and get the median of each half


Why binary search algorithm did not work on an unsorted array?

The binary search algorithm works by successively halving the array and determining which half the result lies in, or if the half-way point is the result. In order for that to work, the array must be in order, otherwise choosing the half-way point would be meaningless because it would not tell you which half of the array the result is located in.


How can you break apart an array to make two arrays?

If the two arrays are a simple division of the larger array (such as splitting it in half), you can use pointers to mark the start address of each sub-array: int a[10]; int* p1 = &amp;a[0]; // point to first half int* p2 = &amp;a[5]; // point to second half You should also use unsigned integer variables to keep track of the size of each sub-array: unsigned p1size = 5, p2size=5; It's usually best to use a structure to keep array pointers and size variables together in one place: typedef struct intarray { int* ptr; unsigned size; } If you need to split the array in a non-contiguous manner you will need to create new arrays that are at least as large as the original array, and then copy the appropriate elements to the appropriate sub-array. Once copied, you can (optionally) shrink the sub-arrays to eliminate any unused elements.


What search algorithm locates an item in an array by repeatedly dividing the array in half?

half means 1/2 from the whole (previous), which means 2 of 1/2, and 2 derived into binary. Ha, Binary Search is the term.


Why is using arrays with loops improve program efficiency?

Arrays provide the most compact method of representing one or more element of the same type in computer memory (whether in working memory or on disk). There is absolutely no memory overhead with arrays, other than when the array is allocated on the heap in which case you need to maintain at least one reference or pointer to the allocated memory. The structure of the array is built-in to the array itself, such that one element immediately follows another, and each element is exactly the same length (in bytes). This makes it possible to access any element in the array in constant time using simple pointer arithmetic. That is, knowing the start address of the array allows you to reference any element in the array using a memory offset or suffix operator. The first element is always found at offset zero (the start of the array) while the next is at offset 1. Thus for an n-element array, the final element will be at offset n-1. By offset, we really mean offset * sizeof (type), where type is the type of each element in the array. However, when working with arrays, the language knows the size of each type therefore we just use the offset as a zero-based index, where element 5 will be found at index 4, which is 4 * sizeof (type) bytes from the start of the array. Given that arrays allow constant-time random access, loops make it extremely easy to traverse arrays from any element to any other element, both forwards and backwards. The loop control variable simply acts as the index to the element we wish to process on each iteration of the loop. We can also choose to skip elements if we're only interested in every other element, or every third element, simply by incrementing the control variable accordingly. Looping through array indices is only efficient when you actually intend to traverse the array, such as when printing the entire array. When searching arrays for a specific value, loop traversal is the least efficient method. If we plan to search an array many times for many different values, it pays to sort the array first. We can then use the binary search technique, starting from the middle element. If that's not our element, the fact the array is sorted means we can eliminate one half of the array, depending on how the middle value compares to the value we are searching for. We then repeat the process with the remaining half, reducing the remaining elements by half each time until we either find our value, or the remaining half has no elements (in which case the value does not exist).

Related questions

How do you find the quartile in an even array of values?

Divide the array in half and get the median of each half


How can you cheat at quizlet scatter games?

It is definitely possible. I've done it myself.here is my method:Create a program that captures an image of the game window. Then, have the program convert the image to black and white, and then an array of booleans, representing either white or black with either 0 or 1. Then, manually, write down the strings or 1s and 0s for each horizontal row of a word (VERY time-consuming). Insert this into an array in the program, have it search the array of booleans, and locate the word. Then, have the program drag the words to the others. For me, this works half the time.


How do i write a program in c langua ge for the implementation of binary search with output?

There are various ways to implement a binary search, but the simplest makes use of a sorted array. It must be sorted because we need to know where values are in relation to one another. That is, if we know that element X has the value Y, then all values less than Y must be in the first half of the array, and all values greater than Y must be in the second half of the array. We begin by looking at the middle element of the array. If there is no middle element (the array is empty) then the value does not exist. But if the middle value holds the value we are looking for, we are done. Otherwise we compare values to decide which half of the array can be eliminated. We then repeat the process with the remaining half of the array.


Why binary search algorithm did not work on an unsorted array?

The binary search algorithm works by successively halving the array and determining which half the result lies in, or if the half-way point is the result. In order for that to work, the array must be in order, otherwise choosing the half-way point would be meaningless because it would not tell you which half of the array the result is located in.


How can you break apart an array to make two arrays?

If the two arrays are a simple division of the larger array (such as splitting it in half), you can use pointers to mark the start address of each sub-array: int a[10]; int* p1 = &amp;a[0]; // point to first half int* p2 = &amp;a[5]; // point to second half You should also use unsigned integer variables to keep track of the size of each sub-array: unsigned p1size = 5, p2size=5; It's usually best to use a structure to keep array pointers and size variables together in one place: typedef struct intarray { int* ptr; unsigned size; } If you need to split the array in a non-contiguous manner you will need to create new arrays that are at least as large as the original array, and then copy the appropriate elements to the appropriate sub-array. Once copied, you can (optionally) shrink the sub-arrays to eliminate any unused elements.


How Write cents as a fraction of 2?

Each cent is one half of 2 cents.


What is full form of HVGA?

Half-size Video Graphics Array


What search algorithm locates an item in an array by repeatedly dividing the array in half?

half means 1/2 from the whole (previous), which means 2 of 1/2, and 2 derived into binary. Ha, Binary Search is the term.


How do you represent binary search and linear search in graphics using c plus plus?

Linear search usually implies the data sequence is in an unsorted order or does not provide random access iterators (such as a list). Essentially you start from the beginning and traverse through each element until you find the element you are looking for, or reach the "one-past-the-end" iterator (which means the value does not exist). With binary search you use a sorted sequence, such as a sorted array. You start in the middle of the sequence. If the value is not there, you know which half of the array the value must be in, so you start in the middle of that half. By eliminating half the array (or sub-array) each time you will either find the value or you end up with an empty sub-array (which means the value does not exist). You can also use binary search on a binary tree which achieves the same thing, but the tree must be perfectly balanced (such as a red/black tree) to be of benefit.


Why is using arrays with loops improve program efficiency?

Arrays provide the most compact method of representing one or more element of the same type in computer memory (whether in working memory or on disk). There is absolutely no memory overhead with arrays, other than when the array is allocated on the heap in which case you need to maintain at least one reference or pointer to the allocated memory. The structure of the array is built-in to the array itself, such that one element immediately follows another, and each element is exactly the same length (in bytes). This makes it possible to access any element in the array in constant time using simple pointer arithmetic. That is, knowing the start address of the array allows you to reference any element in the array using a memory offset or suffix operator. The first element is always found at offset zero (the start of the array) while the next is at offset 1. Thus for an n-element array, the final element will be at offset n-1. By offset, we really mean offset * sizeof (type), where type is the type of each element in the array. However, when working with arrays, the language knows the size of each type therefore we just use the offset as a zero-based index, where element 5 will be found at index 4, which is 4 * sizeof (type) bytes from the start of the array. Given that arrays allow constant-time random access, loops make it extremely easy to traverse arrays from any element to any other element, both forwards and backwards. The loop control variable simply acts as the index to the element we wish to process on each iteration of the loop. We can also choose to skip elements if we're only interested in every other element, or every third element, simply by incrementing the control variable accordingly. Looping through array indices is only efficient when you actually intend to traverse the array, such as when printing the entire array. When searching arrays for a specific value, loop traversal is the least efficient method. If we plan to search an array many times for many different values, it pays to sort the array first. We can then use the binary search technique, starting from the middle element. If that's not our element, the fact the array is sorted means we can eliminate one half of the array, depending on how the middle value compares to the value we are searching for. We then repeat the process with the remaining half, reducing the remaining elements by half each time until we either find our value, or the remaining half has no elements (in which case the value does not exist).


How do you write one-half as a decimal?

We write .5 or 0.5 as the decimal for one half.


How do you write a java program in which the user will enter an amount of money as a decimal number and the program will compute how many pennies nickels dimes quarters ones fives tens twenties etc.?

Denomination values should be stored in an integer array where each value is in pennies. So $100 is 10000 pennies: const array&lt;int,10&gt; value = {10000, 5000, 2000, 500, 100, 50, 25, 10, 5, 1}; Create a parallel array with the actual denominations: const array&lt;string,10&gt; denomination = {"hundreds", "fifties", "twenties", "fives", "dollars", "half", "quarters", "dimes", "nickels", "cents"}; Start by multiplying the amount by 100 to determine the actual number of pennies. So $1.23 becomes 123 pennies. Store this value as an integer named pennies. Now work your way through the denominations in sequence: for (int index=0; index&lt;value.size() &amp;&amp; pennies; ++index) { int number=pennies/value[index]; if (number) cout&lt;&lt;number&lt;&lt;' '&lt;&lt;denomination[index]&lt;&lt;endl; pennies%=value[index]; }