I need help on moving one element of an array to the beginning

Hello! I need assistance on moving one element of an array of strings to the beginning, and keeping the order. For example, let's say I had

string array[10] = {"A","B","C","D","E","F","G","H","I","J"};

When prompted via user input for which string I wanted to move to the beginning—"C" in this case, then the result would be

string array[10] = {"C","A","B","D","E","F","G","H","I","J"};

or if "H" is chosen, then the result would be

string array[10] = {"H","A","B","C","D","E","F","G","I","J"};

If anyone could help me, that would be awesome! I would use a vector, but this is part of a bigger project (this is the only thing I'm stuck on), and the teacher is limiting us to arrays.
You can shift all the elements in an array over by doing this:
for (int i = 0; i < array_size - 1; ++i) array[i + 1] = array[i];

You probably want this:
1
2
for (int i = target - 1; i > 0; -- i)
  words[i] = words[i - 1];


In your case you would want to save the element at the index you're moving to the front, shift all the elements below that index over, and put the saved element into index 0.

Of course, you have to find the index of the element you're moving to the front. That's the upper bound of the loop above. Simple linear search is probably fine (you're stuck at O(n) no matter what):
int i; for (i = 0; i < array_size; ++i) if (array[i] == elt) break;

Don't forget to check that the element was actually found in the array.
if (i == array_size) { uh oh }
Last edited on
Hey mbozzi, I greatly appreciate you for answering my question. However, I'm running into some trouble in trying to implement your advice, and I hope you can offer me some more guidance. Here is what I have right now to test for an algorithm. I am still trying to fix it, so I'll be trying to figure it out while waiting for a reply from you. However, in the case that I give up, I'd want to have the correct answer to refer to.

What I have right now outputs {A, A, C, D, E, F, G, H, I, J} when chosenLetter = "A" ,
{B, B, B, D, E, F, G, H, I, J,} when chosenLetter = "B", and so on.


#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string array[10] = {"A","B","C","D","E","F","G","H","I","J"};
string chosenLetter;
int array_size = sizeof(array)/sizeof(*array);
int indexOfChosenLetter;
//prints array
for (int i = 0; i < array_size; i++){
cout << array[i] << ", ";
}

cout << "Select a letter to put in front of the array" << endl;
cin >> chosenLetter;


for (int i = 0; i < array_size - 1; ++i){
if(array[i] == chosenLetter){
indexOfChosenLetter = i;
}
}

//code I need help with
for (int i = indexOfChosenLetter; i < array_size; ++i){
array[i + 1] = array[i];
if(array[i] == chosenLetter){
array[i] = array[0];
array[0] = chosenLetter;
break;
}
}


//prints array
for (int i = 0; i < array_size; i++){
cout << array[i] << ", ";
}


return 0;
}

EDIT: Help would be appreciated from anyone, as well.
Last edited on
You can iterate through your array and check the position of your character. Store the value of the array using a temp, then use a for loop to shift all of the elements of your array up to that position and place the temp element into the index 0
Last edited on
Hey personxd1, thanks for replying. I'm having problems doing the shifting. Refer to the code above, because it's pretty much what I still have. Sorry for annoying you guys, I'm pretty new to coding in general.
This will be an example.
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>

using namespace std;

void printList(string array[], int array_sz)
{
	int i;
	for(i = 0; i < array_sz; i++)
	{
		cout << array[i];
		if(i != array_sz - 1) cout << ", ";
	}
	cout << endl;
}

int main()
{
	int i;
	string array[10] = {"C","A","B","D","E","F","G","H","I","J"}; int array_sz = (sizeof(array) / sizeof(string));

	cout << "Original list : ";
	printList(array, array_sz);

	string str;
	cout << "Enter the letter to appear at the beginning of the list : "; cin >> str;

	for(i = 0; i < array_sz; i++) 
	{
		if(array[i] == str) break;
	}

	if(i != array_sz && i != 0)
	{
		string temp = array[i];
		array[i] = array[0];
		array[0] = temp;
	}

	cout << "List after : ";
	printList(array, array_sz);

	cin.ignore();
	cin.get();
	return 0;
}
closed account (48T7M4Gy)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string array[] = {"A","B","C","D","E","F","G","H","I","J"};
    string chosenLetter;
    
    int array_size = sizeof(array)/sizeof(string);
    int indexOfChosenLetter = 0;
    
    //prints array
    for (int i = 0; i < array_size; i++){
        cout << array[i] << ", ";
    }
    
    cout << "Select a letter to put in front of the array" << endl;
    cin >> chosenLetter;
    
    
    for (int i = 0; i < array_size; ++i)
    {
        if(array[i] == chosenLetter)
        {
            indexOfChosenLetter = i;
            break;
        }
    }
    
    for(int i = indexOfChosenLetter; i > 0; i--)
    {
        array[i] = array[i-1];
    }
    array[0] = chosenLetter;
    
    //prints array
    for (int i = 0; i < array_size; i++){
        cout << array[i] << ", ";
    }
    cout << endl;
    
    return 0;
}
Last edited on
@kemort
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string array[] = {"A","B","C","D","E","F","G","H","I","J"};
    string chosenLetter;
    
    int array_size = sizeof(array)/sizeof(string);
    int indexOfChosenLetter;
    
    //prints array
    for (int i = 0; i < array_size; i++){
        cout << array[i] << ", ";
    }
    
    cout << "Select a letter to put in front of the array" << endl;
    cin >> chosenLetter;
    
    
    for (int i = 0; i < array_size; ++i)
    {
        if(array[i] == chosenLetter)
        {
            indexOfChosenLetter = i;
            break;
        }
    }
    
    for(int i = indexOfChosenLetter; i > 0; i--)
    {
        array[i] = array[i-1];
    }
    array[0] = chosenLetter;
    
    //prints array
    for (int i = 0; i < array_size; i++){
        cout << array[i] << ", ";
    }
    cout << endl;
    
    return 0;
}

Your example causes Segmentation Fault when the user enters a letter NOT in the list.
That's because I'm a fool: my post is wrong. I'm sorry.

(I know better than to post code that I haven't tested, but I did it anyways.)

Still, the general approach is fine, except that rotating the array needs to be done differently:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

constexpr int ARRAY_SIZE = 6;
std::string const words[ARRAY_SIZE] = {"A", "B", "C", "D", "E", "F"};

void print_words() {
  for (int i = 0; i < ARRAY_SIZE - 1; ++i)
    std::cout << words[i] << ", ";
  std::cout << words[ARRAY_SIZE - 1] << "\n";
}

int main() {
  print_words();
  constexpr int target = 3;
  std::string const target_elt = words[target - 1];

  for (int i = target - 1; i > 0; -- i)
    words[i] = words[i - 1];

  words[0] = target_elt;
  print_words();
}
Last edited on
@mbozzi
Rotating the array is fine, but the assignment does not require you to. You can just swap two array elements and things will turn out well while still being able to preserve the original array elements.
No, you're mistaken. Look again.
To add onto kemort's answer you can create a flag to check whether or not the letter is inside the array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 bool flag;
    for (int i = 0; i < array_size; ++i)
    {
        if(array[i] == chosenLetter)
        {
            flag = true;
            indexOfChosenLetter = i;
            break;
        }
        flag = false;
    }
    
    if(flag==true){
        for(int i = indexOfChosenLetter; i > 0; i--)
        {
            array[i] = array[i-1];
        }
        array[0] = chosenLetter;
    }

This should suffice.
Last edited on
closed account (48T7M4Gy)
And if infinite loops are OK:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string array[] = {"A","B","C","D","E","F","G","H","I","J"};
    string chosenLetter;
    
    int array_size = sizeof(array)/sizeof(string);
    int indexOfChosenLetter = 0; // <---
    
    //prints array
    for (int i = 0; i < array_size; i++)
    {
        cout << array[i] << ", ";
    }
    cout << endl;
    
    while(1)
    {
        cout << "Select a letter to put in front of the array" << endl;
        cin >> chosenLetter;
        
        for (int i = 0; i < array_size; ++i)
        {
            if(array[i] == chosenLetter)
            {
                indexOfChosenLetter = i;
                
                for(int j = indexOfChosenLetter; j > 0; j--)
                {
                    array[j] = array[j-1];
                }
                array[0] = chosenLetter;
                
                //prints array
                for (int k = 0; k < array_size; k++)
                {
                    cout << array[k] << ", ";
                }
                cout << endl;
            }
        }
        cout << "Letter not in list\n";
    }
    
    return 0;
}
Topic archived. No new replies allowed.