fork download
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. // Function to perform Insertion Sort
  6. void insertion_sort(int n, int arr[])
  7. {
  8. cout << "insertion sort" << endl;
  9.  
  10. // Variables to count comparisons and exchanges (shifts)
  11. int cnt_comp = 0, cnt_ex = 0;
  12.  
  13. // Traverse the array starting from the second element
  14. for(int j = 1; j < n; j++)
  15. {
  16. // Store the current element as the key
  17. int key = arr[j];
  18.  
  19. // Index of the previous element
  20. int i = j - 1;
  21.  
  22. // Move elements that are greater than key
  23. // one position ahead of their current position
  24. while(i >= 0 && arr[i] > key)
  25. {
  26. arr[i + 1] = arr[i]; // Shift element to the right
  27. i--;
  28.  
  29. // Count comparison and exchange
  30. cnt_comp++;
  31. cnt_ex++;
  32. }
  33.  
  34. // Count the final comparison that causes loop termination
  35. cnt_comp++;
  36.  
  37. // Insert the key into its correct position
  38. arr[i + 1] = key;
  39. }
  40.  
  41. // Display statistics
  42. cout << "Number of comparisons: " << cnt_comp << endl;
  43. cout << "Number of exchange: " << cnt_ex << endl;
  44. }
  45.  
  46. int main()
  47. {
  48. // Size of the array
  49. int n = 100;
  50.  
  51. // Array declaration (currently uninitialized)
  52. int arr[100];
  53.  
  54. // Example initialized array (uncomment to test)
  55. // int arr[5] = {5, 3, 6, 7, 1};
  56.  
  57. // Call insertion sort function (currently commented out)
  58. // insertion_sort(n, arr);
  59.  
  60. // Print array elements
  61. // Note: Since arr is uninitialized, output will contain garbage values
  62. for(int i = 0; i < 100; i++)
  63. {
  64. cout << arr[i] << " ";
  65. }
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -117514464 5417 0 0 -117538816 5417 -117563360 5417 -117519136 5417 -117541512 5417 -118805242 5417 -117514464 5417 -621038288 32767 -117514464 5417 6 0 6 16 1483374080 -1288768212 0 0 -117518920 5417 -117518920 5417 -117518272 5417 -117510508 5417 -118143029 5417 -117519128 5417 -118370378 5417 -117518552 5417 -117519128 5417 -117520480 5417 -118369376 5417 -117518560 5417 -117518848 5417 -117518560 5417 -118729224 5417 72703 0 -119615224 5417 -118729072 5417 -121329759 5417 -1424797688 21925 -1424797391 21925 1 0 2 0 -621037768 32767 -1424808651 21925 -117376224 5417 0 0