// Problem 3: (5 points) // Swap the strings that are passed as parameters, this
ID: 3665970 • Letter: #
Question
// Problem 3: (5 points) // Swap the strings that are passed as parameters, this function will be used in Problem 4. // If string1 is "hello" and string2 is "goodbye", after calling this function, string1 will be "goodbye" and string2 will be "hello". void swapStrings(char string1[], char string2[]) { } // Problem 4: (20 points) // Use the selection sort algorithm to alphabetically sort the strings in the 2D character array "strings". // If you are unfamiliar with selection sort, here is a visual example: https://en.wikipedia.org/wiki/Selection_sort // NOTE: 'A' and 'a' should be considered alphabetically equivalent. // NOTE: You MUST use the selection sort algorithm for your program to produce the correct output. // NOTE: You MUST incorporate your "swapStrings" function to recieve full points for this part. // See output provided in word document for example input and output. void sortStrings(char strings[5][32]) { }
Explanation / Answer
#include<iostream>
using namespace std;
#include<string.h>
void swapStrings(char string1[], char string2[])
{
int n=strlen(string1);
for(int i=0;i<n;i++)
{
char temp=string1[i];
string1[i]=string2[i];
string2[i]=temp;
}
}
void selectionSort(char word[])
{
int i,j,min;
int n=strlen(word);
char temp;
for(i=0;i<n;i++)
{
if(word[i]>96&&word[i]<123)
{
word[i]=word[i]-32;
}
}
for(i = 0; i < n-1; i++) {
min = i;
for(j = i; j < n; j++) {
if (word[j] < word[min]) {
min = j;
}
}
if( min != i ) {
temp=word[i];
word[i]=word[min];
word[min]=temp;
}
}
}
int main() {
char string1[10],string2[10];
std::cout<<"Enter String1 :";
std::cin>>string1;
std::cout<<" Enter String2 :";
std::cin>>string2;
std::cout<<" String1 before swap : "<<string1;
std::cout<<" String2 before swap : "<<string2;
swapStrings(string1,string2);
std::cout<<" String1 after swap : "<<string1;
std::cout<<" String2 after swap : "<<string2;
int MAX=strlen(string1)+strlen(string2)+1;
char word[MAX];
strcpy(word,string1);
strcat(word,string2);
std::cout<<" String before sort : "<<word;
selectionSort(word);
std::cout<<" String after sort : "<<word;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.