Advertisement
JonathanA007

Binary Insertion Sort (Kelompok 1)

May 3rd, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 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. int Data[MAX], counter_iteration = 0, counter_swap = 0;
  9. // Fungsi pengurutan penyisipan biner
  10. void BinaryInsertSort() {
  11.   int i, j, l, r, m, x;
  12.   for (i = 1; i < MAX; i++) {
  13.     x = Data[i];
  14.     l = 0;
  15.     r = i - 1;
  16.     while (l <= r) {
  17.       m = (l + r) / 2;
  18.       if (x > Data[m])
  19.         r = m - 1;
  20.       else
  21.         l = m + 1;
  22.     }
  23.     for (j = i - 1; j >= l; j--) {
  24.       int y = Data[j];
  25.       int z = Data[j + 1];
  26.       Data[j + 1] = y;
  27.       Data[j] = z;
  28.       counter_swap++;  // Increment swap counter
  29.       printf("\nItem %d dan %d ditukar", y, z);
  30.     }
  31.     Data[l] = x;
  32.  
  33.     // Add cout to display the iteration
  34.     cout << endl << "Iteration " << i << ": ";
  35.     counter_iteration++;
  36.     for (int k = 0; k <= i; k++) {
  37.       cout << Data[k] << " ";
  38.     }
  39.     cout << endl;
  40.   }
  41. }
  42. int main() {
  43.   int i;
  44.   srand(0);
  45.   // Membangkitkan bilangan acak
  46.   printf("DATA SEBELUM TERURUT");
  47.   for (i = 0; i < MAX; i++) {
  48.     Data[i] = (int)rand() / 1000 + 1;
  49.     printf("\nData ke %d : %d ", i, Data[i]);
  50.   }
  51.   printf("\n");
  52.   BinaryInsertSort();
  53.   printf("\n");
  54.   // Data setelah terurut
  55.   printf("\nDATA SETELAH TERURUT");
  56.   for (i = 0; i < MAX; i++) {
  57.     printf("\nData ke %d : %d ", i, Data[i]);
  58.   }
  59.  
  60.   // Display the counter
  61.   cout << endl << endl << "LAPORAN ";
  62.   cout << endl << "Total Iteration: " << counter_iteration;
  63.   cout << endl << "Total Swap And Comparison: " << counter_swap;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement