Rotating array in C++ using single array - c++

I've been recently solving various programming tasks. One that I found was rather easy - array circular rotation. I've chosen C++ as a language and I'd like to keep it.
The idea is to rotate each array element right by a given number of places: e.g. [3, 8, 9, 7, 6] rotated 3 times gives [9, 7, 6, 3, 8].
It wasn't so difficult to figure out solution using extra array. The only required think was new position calculated:
(old_position + rotations)%array_size
However, I've started to think how (if) it can be achieved only with one array? My initial idea was to just swap two elements between new and old position (knowing what old position was) and repeat it for all elements. My code looks like that:
int temp_el;
int temp_index = 0;
int new_pos;
for(int i=0;i<A.size();i++)
{
new_pos = (temp_index + rotations)%A.size();
temp_el = A[new_pos];
A[new_pos] = A[0];
A[0] = temp_el;
temp_index = new_pos;
}
but I forgot about case where in the middle or at the beginning of rotations element at 0 is correct. Which element next I need to pick next? I cannot just take ith element, because it might be already moved.

Related

Why didn't my alternative sorting algorithm work?

I was trying to implement a sorting code so i tried something completely without looking at any other reference codes or anything. Please tell me why my code doesnt show any output? It just runs for sometime and then stops suddenly.
I want to know where i am going wrong. I wanted to take any array as an input and sort the numbers in it in ascending order. So i just iterated throughput the array and compared adjacent elements and swaped them. Then i tried printing the numbers using their indices but it did not print anything on the screen.
#include <iostream>
using namespace std;
int main() {
int arr[6]={1,23,2,32,4,12};
int i=0;
while(i<6)
{
if(arr[i]>arr[i+1])
{
int x = arr[i];
arr[i]=arr[i+1];
arr[i+1]=x;
}
else
continue;
i++;
}
cout<<arr[0];
cout<<arr[1];
cout<<arr[2];
cout<<arr[3];
cout<<arr[4];
cout<<arr[5];
return 0;
}
I expected that the numbers will be printed in ascending order but nothing happened. And also tell me how to print an array all at once.
Thank you
Your sorting algorithm doesn't work because it performs only one pass of a variant of Bubble Sort or Insertion Sort. There has to be one more loop wrapped around your loop to repeat the operation N-1 times.
There are a number of ways to explain why multiple passes are required. Here is one explanation. Whenever we perform this step:
if (arr[i] > arr[i+1])
{
int x = arr[i];
arr[i] = arr[i+1];
arr[i+1] = x;
}
we transfer the arr[i+1] element into the arr[i] position. By doing so, we effectively skip the arr[i+1] element.
Here is what I mean. Suppose arr[i] is called x, arr[i+1] is called y and arr[i+2] is called z. We start with xyz, and exchange x and y to make yxz. But then on the next iteration of the loop, we compare x and z and have forgotten about y; x has moved forward in the array, pushing down y. Why is that a problem? Because y and z have not been compared; and those two are not necessarily in sorted order!
Suppose we have { 3, 2, 0 }. We compare 3 and 2, and swap them, giving us { 2, 3, 0}. Then we move on to comparing 3 and 0: we swap those and get { 2, 0, 3 }. See the problem? We neglected to deal with 2 and 0. That requires another pass through the array.
There is a family of algorithms which work by repeatedly scanning through an array and exchanging items. I suggest studying the following of the common algorithms in this family: insertion sort, selection sort and Shell sort. Also look at bubble sort, in order to understand why it's a poor algorithm compared to either insertion or selection sort that it is closely related to.
your loop condition is incorrect - the last iteration will compare arr[5] and arr[6] which gives index out of bound.
you update your iterator "i" only if you swap, so if your loop encounters the case where arr[i] <= arr[i+1], your iterator will never get updated and your program will run infinitely.
your algorithm implements just a first iteration of bubble sort i.e. it bubbles up (from left to right) the largest number and stops. so the final array looks like [1, 2, 23, 4, 12, 32]

Looking for the best place to insert into a vector

For example if I have a vector of ints
vector<int> my_vector;
my_vector[0] = 6;
my_vector[1] = 3;
So my vector is of size 2 right now.
Now let's say I want to add another integer in my vector. Let's just say this new integer is 10.
I want to be able to set it up 3 (my_vec.size() + 1) ways. In other words, check where placing my new value in my vector of ints would result in the value I'm interested in.
10, 6, 3
6, 10, 3
6, 3, 10
Out of those 3 options, I'll pick the one that best fits my needs. The one I pick, will be my new vector. So if I pick 6, 10, 3, that will be my vector afterwards.
That's the gist of what I want to be able to do.
I have a very inefficient brute force way of creating temp vectors and calculating it that way. I was wondering if there is a simple and optimal way to go about this. I essentially want to be able to compute a new value that I want to add into my vector in all possible areas and look for whatever value I'm interested in.
Just insert new element to the end (most efficient way for the vector) and then move it to the front step by step and test each combination:
vec.push_back( new_value );
test_vector( vec );
for( size_t i = vec.size() - 1; i > 0; --i ) {
std::swap( vec[i], vec[i-1] );
test_vector( vec );
}
live example on ideone for 6,3 + 10. New element will always end at the first position. You need to find best position and then move your element there, that should be pretty obvious.
You really only have 2 cases here. First case: the newly added number is less than the first number in the vector. In this case the number should always be added to the beginning of the vector. If the new number is larger, it should always go in the second spot in the vector (since moving it any farther down the vector will not affect the new total).
I guess I understand your question.
Your computing method is complex. It is a example just now.
Only can you pick a kind of arrangement?
You can implement a function like this:
int GetArrangemnetValue(vector<int>& sourceVec, int nNewPos, int nNewValue);
This function to simulate a whole vetor.
You can do some compute is this function.
Then you can do some select via the return value of funtion.
So you can use this function and not a temporary vector.

Mergsort using pointers rather than indices?

So I need to write a Merge Sort algorithm where,
pointers should be used rather than array indexes to access array elements during the sort, so the method takes 2 int pointers, high and low, and works from there.
Question:
Is it possible to sort the array without indexing it, or does the args should be pointers as opposed to values?
P.S.: Very unfamiliar with pointer operation so thanks for the help!
Since an array is a contiguous block of memory, you can use pointers to access array members much the same as with an index:
int array[] = {1, 2, 3, 4, 5};
int *pointer = array;
int x = *(pointer + 1);
// x = 2
The compiler automatically calculates the offset based on the size of the data: sizeof(int).
So for your project, if you are given a pointer to the first and last elements of the array, You can split the array in the middle:
int *middle = firstPointer + ((lastPointer - firstPointer) / 2);
Then you can keep doing this recursively
Merge sort use sequential access for input from each of two runs (part of an array) and output to a single run (part of the output array). You can use local pointers that you advance by 1 instead of indexing from base pointers. So the main merge process would look something like this:
int * plft = left; // ptr to left run
int * prgt = right; // ptr to right run
int * pdst = destination; // ptr to output
// loop with checks for reaching end of either left or right run
if(*plft <= *prgt) // at some point in the merge function
*pdst++ = *plft++;
else
*pdst++ = *prgt++;
The question doesn't mention if the goal is to implement a top down (use recursion to fill stack with pointers to runs until run size == 1, then start merging and returning) or a bottom up merge sort (skip the recursion step, initialized run size to 1, merge pairs of runs across array until all pairs merged, then run size *= 2, and repeat until run size >= array size).
The wiki article shows simple examples of both top down and bottom up merge sort.
http://en.wikipedia.org/wiki/Merge_sort

How does an index increment work in c++

My tutor told me to use an index to keep track of which character in the line the program is at. How does an index work exactly? I know its similar to count but other than that I am not sure.
At a high level, an index works on a collection. It simply says "I want the nth element of that collection" (where n is your index).
So if you have:
int foo[] = {2, 3, 5, 8, 13}; // array of 5 integers
Using 0 as the index will give you 2, using 1 will give you 3, using 2 will give you 5, using 3 will give you 8 and using 4 will give you 13.
All these are constant indices, so they will always give you the same result. However, if you use a variable as an index, that means you can retrieve a varying element from your collection.
In the case of an array, that collection is simply a block of contiguous memory. The array itself is a memory address, and by adding the index to that memory address, you find the element you're looking for.
By index he just means a pointer to the specific character. This can simply be an integer keeping track of the characters position or an actual pointer type.
string test = "Hello";
const int sLength = 5;
int index = 0;
for ( ; index < sLength ; index++ )
{
cout << "Character at index " << index << " = " << test[index];
}
In the beginning, it helped me to think of indexes as bookmarks. The bookmark keeps track of the last thing at which I was looking.
However, to really understand indexes, you should investigate pointers. You need to understand how structures are stored in memory, what addresses are, and how to sanely move from one address to another.

2-dimensional array, IF condition checking

I've came across a problem when coding with C++ 2D array.
Just a little question, what does the code below mean?
...
if(array[x][y] >= 9){
...
}
...
Does that mean when the sum of x and y of the array is greater or equal to 9, then only the body of the IF will run? Or ........?
Please explain and provide some simply examples.
the array is two dimensional, it means the element at array[x][y]
unlike 1D arrays, which only require 1 index, 2D arrays require 2 indices in the form of array[x][y] presumably in a nested for loop.
You can iterate through such an array like this
for (int x = 0; x < arrayLength; x++) {
for (int y = 0; y < array[x]Length; y++) {
// do something with array[x][y]
}
}
where arrayLength is the length of array and array[x] length is the length of array[x].
So in reference to the code that you posted, it's testing to see if the member of the 2D array is greater than or equal to 9.
Ok let's start with the basics.
1D Arrays
How can you imagine a normal array? You could say a normal array is like a number line:
|-------------------------------| where every - is one element in your array
The very first '-' on the left side is the element at myArray[0] (the '|' are just symbolizing that it has a start and a end).
2D Arrays
A 2D array can be visualized as checkerboard, bookshelf or a table with columns and rows.
|-------------------------------|
|-------------------------------|
|-------------------------------|
|-------------------------------|
Just like in chess you need 2 values in order to address an element. If you only specify one value the compiler might know the row of your value but not its column (or the other way around). That means you need x and y coordinates (which is a visual analogy for a coordinate system). In order to address a value you have to do it like this:
myArray[x][y] where x could be the row of our checkerboard and y the column.
In your case your 2D array is most likely filled with integers. The 'if' statement checks if the value stored in myArray[x][y] is larger than 9. If myArray[x][y] is larger than 9 this statement returns true and the code inside will get executed.
After executing the code inside of the 'if' statement the program will continue to execute the code after the if statement. 2D arrays can be understood as an array containing arrays.
If you are thinking 3 dimensional arrays are possible you're right. Here you need 3 coordinates in order to describe a point since you have depth, height and length (here I'm talking about the visual length not the length in terms of total amount of elements.).
I don't know whether this helped but this is of course a very visual approach of explaining how multi-dimensional arrays work.
Example
int myArray[3][3] = {{1, 2, 3}, // row 0
{4, 5, 6}, // row 1
{7, 8, 10}}; // row 2
In this case your if statement would only be executed if x = 2 and y = 2 since myArray[2][2] = 10
It means "IF the element at coordinates (x,y) is greater or equal than 9...".
There is no addition operation. The array is probably declared with the minimum dimensions (x+1, y+1).
int array[2][2] = {{12, 6}, {3, -2}};
int x=1, y=0;
if(array[x][y] >= 9){...} // array[1][0] equals 3, condition is false