fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. int b_comparisons = 0;
  6. int i_comparisons = 0;
  7. int i_swaps=0;
  8. int b_swaps=0;
  9.  
  10.  
  11. void bubbleSort(int arr[], int n) {
  12. for (int i = 0; i < n - 1; i++) {
  13. bool changed = false;
  14. b_comparisons++;
  15. for (int j = 0; j < n - 1 - i; j++) {
  16. b_swaps++;
  17. if (arr[j] > arr[j + 1]) {
  18.  
  19. int temp = arr[j];
  20. arr[j] = arr[j + 1];
  21. arr[j + 1] = temp;
  22. changed = true;
  23. }
  24. }
  25. if (!changed) break;
  26. }
  27. }
  28.  
  29. void insertionSort(int arr[], int n) {
  30. for (int i = 1; i < n; i++) {
  31. int current = arr[i];
  32. int j = i - 1;
  33. i_comparisons++;
  34. while (j >= 0) {
  35. i_swaps++;
  36. if (arr[j] > current) {
  37. arr[j + 1] = arr[j];
  38. j--;
  39. } else {
  40. break;
  41. }
  42. }
  43.  
  44. arr[j + 1] = current;
  45. }
  46. }
  47.  
  48. void printArray(int arr[], int n) {
  49. for (int i = 0; i < n; i++)
  50. cout << arr[i] << " ";
  51. cout << endl;
  52. }
  53.  
  54. int main() {
  55. int original[] = {5, 3, 8, 4, 2};
  56. int n = 5;
  57.  
  58. int arrBubble[5], arrInsertion[5];
  59. for (int i = 0; i < n; i++) {
  60. arrBubble[i] = original[i];
  61. arrInsertion[i] = original[i];
  62. }
  63.  
  64. bubbleSort(arrBubble, n);
  65. insertionSort(arrInsertion, n);
  66.  
  67. cout << "Бульбашкове сортування "<< endl;
  68. printArray(arrBubble, n);
  69. cout << "Кількість порівнянь: " << b_comparisons<< " "<< b_swaps << endl;
  70.  
  71. cout << "Сортування вставками ";
  72. printArray(arrInsertion, n);
  73. cout << "Кількість порівнянь " << i_comparisons<<" "<< i_swaps << endl;
  74.  
  75. return 0;
  76. }
  77.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Бульбашкове сортування 
2 3 4 5 8 
Кількість порівнянь: 4 10
Сортування вставками 2 3 4 5 8 
Кількість порівнянь 4 9