Write a program to sort the array of character (String) in alphabetical order
Example:
Input: n = 5, arr[]={'g','h','w','s','a'} Output: String after sort is: aghsw
Approach
C
#include <stdio.h>int main(){int n;printf("Enter size of array: ");scanf("%d", &n);char arr[n + 1];printf("Enter the string characters: ");for (int i = 0; i < n + 1; i++)scanf("%c", &arr[i]);for (int i = 0; i < n; i++){for (int j = 0; j < n - i; j++){if (arr[j] > arr[j + 1]){char temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}printf("String after sort is: ");for (int i = 0; i < n + 1; i++)printf("%c", arr[i]);return 0;}
Java
import java.util.Scanner;public class SortCharArray {public static void main(String[] args) {System.out.println("Enter size of array: ");Scanner sc = new Scanner(System.in);int n = sc.nextInt();char arr[] = new char[n];System.out.println("Enter the string characters: ");for (int i = 0; i < n; i++) {arr[i] = sc.next().charAt(0);}for (int i = 0; i < n; i++) {for (int j = 0; j < n - i - 1; j++) {if (arr[j] > arr[j + 1]) {char temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}System.out.println("String after sort is: ");for (int i = 0; i < n; i++) {System.out.printf("%c", arr[i]);}sc.close();}}
No comments:
Post a Comment