In: Computer Science
I'm supposed to create a c++ program which is supposed to take a sentence as an input and then output a sorted list of the occurrence of each letter.
ex.
Enter a phrase: It's a hard knock life
A2
I2
K2
C1
D1
E1
F1
H1
L1
N1
O1
R1
S1
T1
I was also given a recommended code to use as a bubble sort
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */ if A[i-1] > A[i] then
/* swap them and remember something
changed */ swap( A[i-1], A[i] )
swapped = true
end if end for
until not swapped
end procedure
#include <bits/stdc++.h>
using namespace std;
void bubbleSort(string &str)
{
int n = str.length();
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (str[j] > str[j + 1])
{
// swap str[j+1] and str[j]
int temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
}
}
int main() {
string s;
cout<<"Enter a phrase: ";
getline(cin, s);
string str;
for (int i = 0; i < s.length(); ++i) {
if ((s[i] <= 'z' && s[i] >= 'a') || (s[i] <= 'Z' && s[i] >= 'A')) {
str += toupper(s[i]);
}
}
bubbleSort(str);
for (int i = 0; i < str.length(); ++i) {
cout << str[i];
int cnt = 0;
if(i == str.length()-1){
cout<<1<<endl;
break;
}
while (str[i] == str[i + 1]) {
i++;
cnt++;
}
cout<<cnt+1<<endl;
}
return 0;
}
OUTPUT: