Advertisement
avv210

bubbleSort and selectionSort

Feb 26th, 2022
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. // SortingAlgorithm.cpp : This file contains the 'main' function. Program execution begins and ends there.
  2. #include <iostream>
  3.  
  4. void swap(int& el1, int& el2)
  5. {
  6.     int temp = el1;
  7.     el1 = el2;
  8.     el2 = temp;
  9. }
  10.  
  11. void bubbleSort(int arr[], int arrSize)
  12. {
  13.     // Scan all the entire list/array
  14.     for (int cursor = 0; cursor < arrSize; cursor++)
  15.         // Iterate from i to i+1 position
  16.         for (int i = 0; i < arrSize - cursor - 1; i++)
  17.             // compare both element
  18.             // if left > right
  19.             if (arr[i] > arr[i + 1])
  20.                 // then swap the element to correct position
  21.                 swap(arr[i], arr[i+1]);
  22. }
  23.  
  24. void selectionSort(int arr[], int arrSize)
  25. {
  26.     for (int i = 0; i < arrSize - 1; i++)
  27.     {
  28.         int currMin = i;
  29.         for (int currItem = i + 1; currItem < arrSize; currItem++)
  30.             if (arr[currMin] > arr[currItem])
  31.                 currMin = currItem;
  32.         swap(arr[currMin], arr[i]);
  33.     }
  34. }
  35.  
  36. void printArr(int arr[], int arrSize)
  37. {
  38.     for (int i = 0; i < arrSize; i++)
  39.         std::cout << arr[i] << " ";
  40.     std::cout << "\n\n";
  41. }
  42.  
  43. int main()
  44. {
  45.     int arr[] = { 10, 11, 1, -2, 5 };
  46.     int size = sizeof(arr) / sizeof(arr[1]);
  47.     // bubbleSort(arr, size);
  48.     selectionSort(arr, size);
  49.     std::cout << "Sorted data: ";
  50.     printArr(arr, size);
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement