156k views
2 votes
Write a function that will alphabetize a string WITHOUT using the sort function :

void alphabetize(string &s) {

}

1 Answer

4 votes

Answer:

here is code in C++.

#include <bits/stdc++.h>

using namespace std;

// function to alphabetize the input string

void alphabetize(string &str)

{

// find the length of string

int n=str.size();

for(int x=0;x<n;x++){

for(int y=x+1;y<n;y++)

{

//swap the character

if(str[x]>str[y]){

char ch=str[x];

str[x]=str[y];

str[y]=ch;

}

}

}

cout<<"alphabetize string is: "<<str<<endl;;

}

int main()

{// string variable to read input

string inp;

cout<<"Please Enter a String in lowercase :";

//reading the input

cin>>inp;

// call function with inp argument

alphabetize(inp);

return 0;

}

Step-by-step explanation:

Declare a variable "inp" of string type and assign the input string to it. call the alphabetize() function with argument "inp".In the alphabetize(),find the length of input string.Then travers the string and if a character is greater than any next character in the string then swap it, so that all the character are sorted.

Output:

Please Enter a String in lowercase :helloworld

alphabetize string is: dehllloorw

User Art Vanderlay
by
5.5k points