Computer Science, asked by preksham, 5 hours ago

write a program in java to enter 10 characters into a character array and sort the array into ascending order using bubble sort technique.

Answers

Answered by SƬᏗᏒᏇᏗƦƦᎥᎧƦ
41

Your required program :-

import.java.util.scanner

public class BubbleSort

{

public static void main (String args [ ])

{

char list [ ] = {'S' , 'T' , 'A' , 'R' , 'W' , 'A' , 'R' , 'I' , 'O' , 'R'} ;

int len = 0 ; list.length ;

for (int i = 0 ; i < len - i ; i ++)

{

for (int j = 0 ; i < len - i - 1 ; j ++)

{

if (list [j] < list [j + 1])

{

char tmp = list [j] ;

list [j] = list [j + 1]) ;

list [j + 1] = tmp;

}

}

System.out.println (" Array in descending order is : ");

for (int i = 0 ; i < len; i ++)

{

System.out.println (list [i]);

}

}

Explanation :-

  • Line 1 : Util package of java is been used for this program.
  • Line 4 : We have used - (String args [ ]) because we have to enter characters.
  • Line 6 : List of characters (char list ) has been entered. And ten characters we've entered are:- S , T , A , R , W , A , R , R , I , O , R.
  • Line 7 : Length of character (char) is entered.
  • Line 9 : For loop is runned in reverse order
  • Line 11 : Loop is runned in reverse order for jth position.
  • Line 13 : Checking if the element at the jth position is less than at the (j + 1)th position.
  • Line 16 : Value of the current character (char) is been stored in a temporary variable.
  • Line 17 : Value of the next element of the array is stored.
  • Line 18 : Value of temporary variable is stored in the other element.
  • Line 21 : Array in descending order is printed

Answered by samarthkrv
1

Answer:

import java.util.Scanner;

public class sort

{

   static void bubble_sort(char[] arr){

       int n = arr.length;

       for(int i = 0; i < n-1; i++){

           for(int j = i+1; j < n; j++){

               if(arr[i] > arr[j]){

                   char temp = arr[i];

                   arr[i] = arr[j];

                   arr[j] = temp;

               }

           }

       }

   }

public static void main(String[] args) throws Exception {

 Scanner sc = new Scanner(System.in);  

 char[] arr = new char[10];

 System.out.println("Enter all 10 characters-");

     for(int i = 0; i < 10; i++){

         arr[i] = sc.next().charAt(0);

     }

           System.out.println("BEFORE SORTING");      

     for(int i = 0; i < 10; i++){

         System.out.print(arr[i] + " ");

     }

     bubble_sort(arr);

     System.out.println("\nAFTER SORTING");

     for(int i = 0; i < 10; i++){

         System.out.print(arr[i] + " ");

     }

}

}

Explanation:

Similar questions