fork download
  1. import java.util.Arrays;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. // Example array of integers
  8. int[] array = {5, 3, 8, 2, 1};
  9.  
  10. System.out.println("Sorted Array: " + Arrays.toString(array));
  11.  
  12. // Sorting the array using Selection Sort
  13. BubbleSort(array);
  14.  
  15. // Displaying the sorted array
  16. System.out.println("Sorted Array: " + Arrays.toString(array));
  17. }
  18.  
  19. // Implementation of Selection Sort algorithm
  20. public static void BubbleSort(int[] array) {
  21.  
  22. int n = array.length;
  23. boolean swapped,
  24. finished = false;
  25.  
  26. while(!finished) {
  27. swapped = false;
  28. for (int i = 0; i < n - 1; i++) {
  29. if(array[i]>array[i+1]){
  30. int tmp = array[i];
  31. array[i] = array[i+1];
  32. array[i+1] = tmp;
  33. swapped = true;
  34. }
  35. }
  36. if(swapped) n--;else finished = true;
  37. }
  38. }
  39. }
Success #stdin #stdout 0.14s 55480KB
stdin
Standard input is empty
stdout
Sorted Array: [5, 3, 8, 2, 1]
Sorted Array: [1, 2, 3, 5, 8]