Sorting a string with Bubble sort algorithm C++

ASCII code is associated with each character. Suppose we have a string “t4tutorials”. We can arrange the characters in ascending or descending order with the help of ASCII codes. All this mechanism is known as sorting.
There are different sorting techniques to sort the string, such as selection sort, insertion sort, Quicksort, etc.
Here, I am showing you the bubble sort method to sort. the name(first name, last name, etc).

Algorithm of Sorting a string with Bubble sort in C++

  1. We take a string as input. (e.g we can take the name of our website t4tutorials as a string)
  2. Next, we will use nested for loop to compare and traverse the string.
  3. Comparison: if the previous element is smaller than the next element, then do nothing.
  4. if the previous element is not smaller than the next element, then swap the characters.
  5.  Print the sorted string. (e.g we can take the name of our website t4tutorials as a string we can sort it as “4ailorstttu)

Bubble sort a string of last name or  first name in C++

#include <iostream>
#include <string>
using namespace std;
int main ()
{
    string str="t4tutorials"; 
    int Length = str.length();
    cout<<"\n String before sorting is: "<<str<<" \n";  
    //using bubble sort to sort the characters inside a name 
    for (int i = 0; i < Length; i++)
	{
        for (int j = i+1; j < Length; j++)
	    {
            if (str[i] > str[j]) 
			//to check that previous value has bigger ascii value than next value or not,
	    {
		//code to swap the previous and next characters
                char temporary = str[i];
                str[i] = str[j];
                str[j] = temporary;
            }
        }   
    }
    cout<<"\n String after sorting is: "<<str<<" \n";
    return 0;
}

Output

String before sorting is: t4tutorials

String after sorting is: 4ailorstttu

Bubble sort an array of integer values in C++

#include<iostream>
 
using namespace std;
 
int main()
{
    int array[50];
	int s;
	int i;
	int j;
	int t;
	
    cout<<"Please enter the size of array: ";
    cin>>s;
    
    cout<<"Please enter the values into array: "; 
    
    for(i=0;i<s;++i)
        cin>>array[i];
        
    for(i=1;i<s;++i)
    {
        for(j=0;j<(s-i);++j)
            if(array[j]>array[j+1])
            {
                t=array[j];
                array[j]=array[j+1];
                array[j+1]=t;
            }
    }
    
    cout<<"Array after sorting is:";
    
    for(i=0;i<s;++i)
        cout<<" "<<array[i];
        
    return 0;
}

Output:

Program to implement Bubble Sort in CPP (C plus plus)
Program to implement Bubble Sort in CPP (C plus plus)
Prof.Fazal Rehman Shamil (Available for Professional Discussions)
1. Message on Facebook page for discussions,
2. Video lectures on Youtube
3. Email is only for Advertisement/business enquiries.