Advertisement
hisyam99

Selection Sort Algorithm

Oct 16th, 2023 (edited)
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | Source Code | 0 0
  1. //Muhammad Hisyam Kamil
  2. //Algoritma Pemrograman 3A
  3. //Selection Sort
  4.  
  5. import java.util.Arrays;
  6. import java.util.Random;
  7.  
  8. public class SelectionSort {
  9.     public static void selectionSort(int[] arr) {
  10.         int n = arr.length;
  11.  
  12.         for (int i = 0; i < n - 1; i++) {
  13.             int minIndex = i;
  14.  
  15.             for (int j = i + 1; j < n; j++) {
  16.                 if (arr[j] < arr[minIndex]) {
  17.                     minIndex = j;
  18.                 }
  19.             }
  20.  
  21.             int temp = arr[minIndex];
  22.             arr[minIndex] = arr[i];
  23.             arr[i] = temp;
  24.  
  25.             System.out.println("Iterasi ke-" + (i + 1) + ": " + Arrays.toString(arr));
  26.         }
  27.     }
  28.  
  29.     public static void main(String[] args) {
  30.         int[] arr = generateRandomArray(10);
  31.  
  32.         System.out.println("Array sebelum Selection Sort: " + Arrays.toString(arr));
  33.         long startTime = System.nanoTime();
  34.         selectionSort(arr);
  35.         long endTime = System.nanoTime();
  36.  
  37.         System.out.println("Array setelah Selection Sort: " + Arrays.toString(arr));
  38.  
  39.         long executionTime = endTime - startTime;
  40.         double executionTimeMilliseconds = (double) executionTime / 1_000_000.0;
  41.         System.out.println("Waktu eksekusi Selection Sort (nanoseconds): " + executionTime + " ns");
  42.         System.out.println("Waktu eksekusi Selection Sort (milliseconds): " + executionTimeMilliseconds + " ms");
  43.     }
  44.  
  45.     public static int[] generateRandomArray(int size) {
  46.         int[] arr = new int[size];
  47.         Random random = new Random();
  48.         for (int i = 0; i < size; i++) {
  49.             arr[i] = random.nextInt(20);
  50.         }
  51.         return arr;
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement