VelizarAng

BubbleSort (DoWhile loop)

Nov 2nd, 2020 (edited)
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class BubbleSort {
  5.     public static void BubbleSort(int[] ARR){
  6.         int j, Buff;
  7.         boolean swap;
  8.        
  9.         do{
  10.            swap = false;
  11.            for (j = 0; j < ARR.length - 1; j++) {
  12.                 if(ARR[j] > ARR[j + 1]){
  13.                     swap = true;
  14.                     Buff = ARR[j];
  15.                     ARR[j] = ARR[j + 1];
  16.                     ARR[j + 1] = Buff;
  17.                 }
  18.             }
  19.         }while(swap);
  20.     }
  21.  
  22.     public static void main(String[] args) {
  23.         //point 1
  24.         Scanner scan = new Scanner(System.in);
  25.         System.out.println("Input number of elements: ");
  26.         int n = scan.nextInt();
  27.  
  28.         //point 2
  29.         int[] ARR = new int[n];
  30.  
  31.         //point 3
  32.         for (int i = 0; i < n ; i++) {
  33.             System.out.printf("Please input element [%d]", i);
  34.             ARR[i] = scan.nextInt();
  35.         }
  36.  
  37.         //point 4
  38.         System.out.println("BEFORE SORTING: ");
  39.         System.out.println(Arrays.toString(ARR));
  40.  
  41.         //point 5
  42.         BubbleSort(ARR);
  43.  
  44.         //point 6
  45.         System.out.println("AFTER SORTING: ");
  46.         System.out.println(Arrays.toString(ARR));
  47.  
  48.     }
  49. }
  50.  
Add Comment
Please, Sign In to add comment