Each character has an ASCII code associated with it. In a given string, arranging the characters, according to the ASCII codes, in ascending or descending order, is known as sorting. The example given below uses the bubble sort method to sort. One can also use other sorting techniques such as selection sort, insertion sort, Quick sort, etc.

Note: ASCII codes of capital letters are lesser than those of the lower case.

Logic:

In this method, we’ll take up each character and check if it is smaller than the next character, if yes, then we’ll swap the positions of the character else do nothing.

Algorithm:

  1. Take a string as input.
  2. Use nested for loop to compare and traverse the string.
  3. Now, check if the previous element is smaller than the next element, if yes, then do nothing.
  4. If no, then swap the characters.
  5. Print the sorted string.

Code:

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string str;
    cout<<"Enter the string to be sorted: ";
    getline(cin,str); 
    int len = str.length();
    cout<<"\n String before sorting: "<<str<<" \n";
    
    //using bubble sort to sort the characters
    for (int i = 0; i < len; i++)
	{
        for (int j = i+1; j < len; j++)
	    {
            if (str[i] > str[j]) //if previous has bigger ascii value than next,
	    {
		//swapping the prev and next characters
                char temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }   
    }
    cout<<"\n String after sorting: "<<str<<" \n";
    return 0;
}

Output:

Enter the string to be sorted: quick brown fox jumps over the lazy dog
String before sorting: quick brown fox jumps over the lazy dog

String after sorting: abcdeefghijklmnoooopqrrstuuvwxyz

[yuzo_views]












CopyRight © 2019

CopyRight © 2019