Java Day 20: Sorting



Given an array, a, of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following 3 lines:



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. public class Solution {
  7. public static void main(String[] args) {
  8. Scanner in = new Scanner(System.in);
  9. int n = in.nextInt();
  10. int arr[] = new int[n];
  11. for (int i = 0; i < n; i++) {
  12. arr[i] = in.nextInt();
  13. }
  14. int numSwaps = 0;
  15. for (int i = 0; i < n; i++) {
  16. for (int j = 0; j < n - 1; j++) {
  17. if (arr[j] > arr[j + 1]) {
  18. int tmp = arr[j];
  19. arr[j] = arr[j + 1];
  20. arr[j + 1] = tmp;
  21. numSwaps++;
  22. }
  23. }
  24. if (numSwaps == 0) {
  25. break;
  26. }
  27. }
  28. System.out.println("Array is sorted in " + numSwaps + " swaps.");
  29. System.out.println("First Element: " + arr[0]);
  30. System.out.println("Last Element: " + arr[arr.length - 1]);
  31. }
  32. }