Advertisement
JonathanA007

Selection Sort (Kelompok 1)

May 3rd, 2024
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #define MAX 50
  5.  
  6. using namespace std;
  7.  
  8.  
  9. int Data[MAX];
  10. int counter_iteration = 0, counter_swap = 0 , counter_compare = 0;
  11. // Fungsi pertukaran bilangan
  12. void Tukar(int *a, int *b) {
  13.   counter_swap++;
  14.   cout << "\nItem " << *a << " dan " << *b << " ditukar";
  15.   int temp;
  16.   temp = *a;
  17.   *a = *b;
  18.   *b = temp;
  19. }
  20. // Fungsi pengurutan penyisipan biner
  21. void SelectionSort() {
  22.   int i, j, k;
  23.   for (i = 0; i < MAX - 1; i++) {
  24.     k = i;
  25.     counter_iteration++;
  26.     for (j = i + 1; j < MAX; j++){
  27.       counter_compare++;
  28.       if (Data[k] < Data[j]) k = j; // Pengaturan ASC dan DESC ada di sini
  29.     }
  30.     Tukar(&Data[i], &Data[k]);
  31.  
  32.     cout << endl ;
  33.     for (int k = 0; k < MAX; k++) {
  34.       cout << Data[k] << " ";
  35.     }
  36.     cout << endl;
  37.   }
  38. }
  39. int main() {
  40.   int i;
  41.   srand(0);
  42.   // Membangkitkan bilangan acak
  43.   printf("DATA SEBELUM TERURUT");
  44.   for (i = 0; i < MAX; i++) {
  45.     Data[i] = (int)rand() / 1000 + 1;
  46.     printf("\nData ke %d : %d ", i, Data[i]);
  47.   }
  48.   printf("\n");
  49.   SelectionSort();
  50.   printf("\n");
  51.   // Data setelah terurut
  52.   printf("\nDATA SETELAH TERURUT");
  53.   for (i = 0; i < MAX; i++) {
  54.     printf("\nData ke %d : %d ", i, Data[i]);
  55.   }
  56.  
  57.   // Display the counter
  58.   cout << endl << endl << "Laporan" ;
  59.   cout << endl << "Total Iteration: " << counter_iteration;
  60.   cout << endl << "Total Swap: " << counter_swap;
  61.   cout << endl << "Total Compare: " << counter_compare;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement