Cs 201 Assgnment Solution

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

cs 201 assgnment solution

#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];

c << "For arrays A1 and A2, enter up to " << N << endl;
c << "characters (not counting spaces)" << endl;
c << "A1 > ";
getline(cin,line);
for (i = line.begin(), j = 0; (i != line.end()) && (j < N); i++) {
if (*i != space) a1[j++] = *i;
}
c << "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];
}
}
c << "Merged : ";
printArray(merged);

// Sort
selectionSort(merged,k);

c << "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++) {

c << a[i] << " ";


}

c << 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

You might also like