a. Given the following array of 8 integers {2,3,2,1,2,5,8,2} you are required to write a
C++ program that will loop through it and re-arrange it into the following final output
{5,3,1,8,2,2,2,2} and display it . The idea is to position all values equal to 2 in the
array to come after the other values not equal to 2. The order of the other values i.e 5,1,3
and 8 does not matter as long as they appear positioned before all 2s as illustrated in the hint
below:
Initial array: {2,3,2,1,2,5,8,2}
NumbertoMove = 2
Final Array: {5,3,1,8,2,2,2,2}
Write an algorithm as a pseudocode to solve the problem above. [7 Marks]
b. Transform the pseudocode in part (a) above into an actual C++ program that filters all
values equal to 2 in the array to come after the other values not equal to 2. The order of the
other values i.e 5,1,3 and 8 does not matter as long as they appear positioned before all 2s.
Pseudocode
1 Set insert_i to array length
2 If elemen at position insert_i is not equal 2 go to step 5
3 Decrease insert_i by 1
4 Go to step 2
5 Set check_i to 1
6 If element at position check_i equal 2
7 Swap elements at positions check_i and insert_i
8 Decrement insert_i by 1
9 Increment check_i by 1
10 If check_i is less than insert_i go to step 6
C++ code:
#include <iostream>
using namespace std;
void PrintArray(int a[], int n) {
for (int i=0; i<n; i++) {
cout << a[i] << " ";
}
cout << endl;
}
void Swap(int&a, int& b) {
int tmp = a;
a = b;
b = tmp;
}
int main() {
int arr[] = {2,3,2,1,2,5,8,2};
int n = sizeof(arr) / sizeof(arr[0]);
PrintArray(arr, n);
int j=n-1, i=0;
while (arr[j] == 2) {
j--;
}
while ( i < j ) {
if (arr[i] == 2) {
Swap(arr[i], arr[j]);
j--;
}
i++;
}
PrintArray(arr, n);
}
Comments
Leave a comment