Write a program to Sort the string
Example:
Input: str: "ramsingh"
Output: aghimnrs
Approach: Using the inbuilt method
Java
import java.util.Arrays;public class StringSort {public static void main(String[] args) {String s = "ramsingh";System.out.println(strSort(s));}private static String strSort(String s) {char ch[] = s.toCharArray();Arrays.sort(ch);return new String(ch);}}
C++
#include <bits/stdc++.h>using namespace std;string strSort(string s){sort(s.begin(),s.end());return s;}int main(){string s = "ramsingh";cout<<strSort(s);return 0;}
Approach: Using bubble sort
Java
import java.util.Arrays;public class StringSort {public static void main(String[] args) {String s = "ramsingh";System.out.println(strSort(s));}private static String strSort(String s) {char ch[] = s.toCharArray();int size = ch.length;for (int i = 0; i < size; i++) {for (int j = i + 1; j < size; j++) {if (ch[i] > ch[j]) {char temp = ch[i];ch[i] = ch[j];ch[j] = (char) temp;}}}return new String(ch);}}
C++
#include <bits/stdc++.h>using namespace std;string strSort(string s){vector<char> ch;for(int i=0;i<s.size();i++)ch.push_back(s[i]);int size = ch.size();for (int i = 0; i < size; i++) {for (int j = i + 1; j < size; j++) {if (ch[i] > ch[j]) {char temp = ch[i];ch[i] = ch[j];ch[j] = (char) temp;}}}s="";for(int i=0;i<size;i++)s+=ch[i];return s;}int main(){string s = "ramsingh";cout<<strSort(s);return 0;}
No comments:
Post a Comment