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++
- We take a string as input. (e.g we can take the name of our website t4tutorials as a string)
- Next, we will use nested for loop to compare and traverse the string.
- Comparison: if the previous element is smaller than the next element, then do nothing.
- if the previous element is not smaller than the next element, then swap the characters.
- 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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#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++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#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:
