Advertisement
TermSpar

Basic Search Algorithms

Mar 21st, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. void bubbleSort(int[], int);
  7. void swapVals(int*, int*);
  8. void selectionSort(int[], int);
  9.  
  10. int main()
  11. {
  12.     int array1[9] = { 2, 4, 9, 1, 19, 3, 11, 8 };
  13.  
  14.     cout << "Bubble sort (Original):\n ";
  15.     for (int i = 0; i < 8; i++) {
  16.         cout << array1[i] << " ";
  17.     }
  18.     bubbleSort(array1, 8);
  19.  
  20.     int array2[9] = { 2, 4, 9, 1, 19, 3, 11, 8 };
  21.     cout << "\nSelection sort (Original):\n ";
  22.     for (int i = 0; i < 8; i++) {
  23.         cout << array2[i] << " ";
  24.     }
  25.     selectionSort(array2, 8);
  26.  
  27.     system("pause");
  28. }
  29.  
  30. void bubbleSort(int ray[], int size) {
  31.     bool change = false;
  32.     cout << "\nBubble sort (Steps):\n ";
  33.     int steps = 1;
  34.  
  35.     do {
  36.         change = false;
  37.         for (int i = 0; i < size; i++) {
  38.             if (ray[i + 1] != NULL) {
  39.                 if (ray[i] > ray[i + 1]) {
  40.                     int temp = ray[i];
  41.                     ray[i] = ray[i + 1];
  42.                     ray[i + 1] = temp;
  43.                     change = true;
  44.                 }
  45.             }
  46.         }
  47.  
  48.         cout << "Step #" << steps << ": ";
  49.         for (int i = 0; i < size; i++) {
  50.             cout << ray[i] << " ";
  51.         }
  52.         steps++;
  53.         cout << "\n";
  54.     } while (change);
  55. }
  56.  
  57. void swapVals(int *val1, int *val2)
  58. {
  59.     int temp = *val1;
  60.     *val1 = *val2;
  61.     *val2 = temp;
  62. }
  63.  
  64. void selectionSort(int ray[], int size) {
  65.     cout << "\nSelection sort (Steps):\n ";
  66.  
  67.     int minVal = ray[0];
  68.     int steps = 1;
  69.  
  70.     for (int i = 0; i < size; i++) {
  71.         minVal = i;
  72.         for (int j = i + 1; j < size; j++) {
  73.             if (ray[j] < ray[minVal]) {
  74.                 minVal = j;
  75.             }
  76.         }
  77.         swapVals(&ray[minVal], &ray[i]);
  78.  
  79.         cout << "Step #" << steps << ": ";
  80.         for (int i2 = 0; i2 < size; i2++) {
  81.             cout << ray[i2] << " ";
  82.         }
  83.         cout << "\n";
  84.         steps++;
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement