Vankata17

DO WHILE BUBBLE SORT

Oct 21st, 2020
641
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.company;
  2.  
  3. import java.lang.reflect.Array;
  4. import java.util.Arrays;
  5. import java.util.Scanner;
  6.  
  7. public class Algorithm4 {
  8.     public static void main(String[] args) {
  9.         Scanner scan = new Scanner(System.in);
  10.         System.out.print("Please input the number of elements :");
  11.         int n = Integer.parseInt(scan.nextLine());
  12.         char[] arr = new char[n]; // Define array for elements
  13.  
  14.         for (int i = 0; i < n; i++) // Input values to array
  15.         {
  16.             System.out.printf("Please insert the [%d] element of array :", i);
  17.             arr[i] = scan.next().charAt(0);
  18.         }
  19.         System.out.println("BEFORE SORTING :");
  20.         System.out.println(Arrays.toString(arr));
  21.  
  22.         boolean swap;
  23.         do {
  24.             swap = false;
  25.             for (int i = 0; i < arr.length - 1; i++) {
  26.                 if (arr[i] > arr[i + 1]) {
  27.                     int free = arr[i];
  28.                     arr[i] = arr[i + 1];
  29.                     arr[i + 1] = (char) free;
  30.                     swap = true;
  31.                 }
  32.             }
  33.         } while (swap) ;
  34.  
  35.         System.out.println("AFTER SORTING :");
  36.         System.out.println(Arrays.toString(arr));
  37.  
  38.  
  39.     }
  40. }
  41.  
RAW Paste Data