Advertisement
JonathanA007

Straight Insertion Sort (Kelompok 1)

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