Problem Statement: Merging and Sorting of characterarrays Detailed Description:
ID: 3614989 • Letter: P
Question
Problem Statement: Merging and Sorting of characterarrays
Detailed Description:
1. Declare three character type arrays.
2. Use two arrays to take input from user.
o Take input as chartype.
o Take 10 values in eacharray.
3. Merge both these input arrays.
o If an input character isin both arrays, then it should appear once in resulted array.
4. Store result in third array.
5. Sort resulted array in ascending order.
o Ascending order meansstring values starting from ‘a’ will come first, andthen starting from ‘b’ and so on.
6. Display them after sorting
Sample Output
Enter values in first array: a h b c u v I j k e
Enter values in Second array: y u d f g k I w q a
Merged array: a y h u b d c f g v k I j w q e
Sorted Array in ascending order: a b c d e f g h I j k q uv w y
Explanation / Answer
Solution According to the question / assignment #include <iostream>#include <string>
#include <cstring>
#include <cctype>
using namespace std;
const size_t N = 10;
const char space = ' ';
void selectionSort(char *, size_t length);
void printArray(const char *);
int main(int argc, char *argv[]) {
string line;
string::iterator i;
size_t j, k;
char *a1 = new char[N],
*a2 = new char[N],
*merged = new char[N*2];
cout << "For arrays A1 and A2, enter up to "<< N << endl;
cout << "characters (not counting spaces)"<< endl;
cout << "A1 > ";
getline(cin,line);
for (i = line.begin(), j = 0; (i != line.end())&& (j < N); i++) {
if (*i != space) a1[j++] = *i;
}
cout << "A2 > ";
getline(cin,line);
for (i = line.begin(), j = 0; (i != line.end())&& (j < N); i++) {
if (*i != space) a2[j++] = *i;
}
// Merge
for (j = 0, k = 0; j < N; j++) {
merged[k++] = a1[j];
if (strchr(a1,a2[j]) == NULL) {
merged[k++] = a2[j];
}
}
cout << "Merged : ";
printArray(merged);
// Sort
selectionSort(merged,k);
cout << "Sorted : ";
printArray(merged);
delete [] a1;
delete [] a2;
delete [] merged;
return 0;
}
void printArray(const char *a) {
for (size_t i = 0; i < strlen(a); i++) {
cout << a[i] << " ";
}
cout << endl;
}
//
// Selection sort of a char array, ignoring case.
//
void selectionSort(char *a, size_t n) {
char min, t;
for (size_t i = 0; i < n; i++) {
min = i;
for (size_t j = i+1; j < n; j++){
if (tolower(a[j]) <tolower(a[min])) {
min =j;
}
}
t = a[min];
a[min] = a[i];
a[i] = t;
}
}
#if 0
Sample run:
For arrays A1 and A2, enter up to 10
characters (not counting spaces)
A1 > a h b c u v I j k e
A2 > y u d f g k I w q a
Merged : a y h b d c f u g v I j w k q e
Sorted : a b c d e f g h I j k q u v w y
#endif
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.