fork download
  1. import java.util.Arrays;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5.  
  6. // Example array of integers
  7. int[] array = {5, 3, 8, 2, 1};
  8.  
  9. System.out.println("Sorted Array: " + Arrays.toString(array));
  10.  
  11. // Sorting the array using Selection Sort
  12. selectionSort(array);
  13.  
  14. // Displaying the sorted array
  15. System.out.println("Sorted Array: " + Arrays.toString(array));
  16. }
  17.  
  18. // Implementation of Selection Sort algorithm
  19. public static void selectionSort(int[] array) {
  20. int n = array.length;
  21.  
  22. for (int i = 0; i < n - 1; i++) {
  23. // Assume the current index is the minimum
  24. int minIndex = i;
  25.  
  26. // Find the index of the minimum element in the unsorted part of the array
  27. for (int j = i + 1; j < n; j++) {
  28. if (array[j] < array[minIndex]) {
  29. minIndex = j;
  30. }
  31. }
  32.  
  33. // Swap the found minimum element with the element at the current index
  34. int temp = array[minIndex];
  35. array[minIndex] = array[i];
  36. array[i] = temp;
  37. }
  38. }
  39. }
Success #stdin #stdout 0.1s 55452KB
stdin
Standard input is empty
stdout
Sorted Array: [5, 3, 8, 2, 1]
Sorted Array: [1, 2, 3, 5, 8]