fork download
  1. //
  2. // main.cpp
  3. // Sorting Algorithms
  4. //
  5. // Created by Himanshu on 21/09/21.
  6. //
  7.  
  8. #include <iostream>
  9. using namespace std;
  10.  
  11. void printArray (int arr[], int n) {
  12. for (int i=0; i<n; i++) {
  13. cout<<arr[i]<<" ";
  14. }
  15. cout<<endl;
  16. }
  17.  
  18.  
  19. void BubbleSort (int arr[], int n) {
  20. for (int i=0; i<n; i++) {
  21. for (int j=0; j<n-i-1; j++) {
  22. if (arr[j+1] < arr[j]) {
  23. swap (arr[j], arr[j+1]);
  24. }
  25. }
  26. printf("Array after %d iteration: \n", i+1);
  27. printArray(arr, n);
  28. }
  29. }
  30.  
  31. void InsertionSort (int arr[], int n) {
  32. for (int i=1; i<n; i++) {
  33. int j = i;
  34. while (j>0 && arr[j-1] > arr[j]) {
  35. swap (arr[j-1], arr[j]);
  36. j--;
  37. }
  38. printf("Array after %d iteration: \n", i);
  39. printArray(arr, n);
  40. }
  41. }
  42.  
  43. void SelectionSort (int arr[], int n) {
  44. for (int i=0; i<n; i++) {
  45. int indexMin = i;
  46. for (int j = i+1; j<n; j++) {
  47. if (arr[j] < arr[indexMin]) {
  48. indexMin = j;
  49. }
  50. }
  51. if (indexMin != i) {
  52. swap (arr[indexMin], arr[i]);
  53. }
  54. printf("Array after %d iteration: \n", i+1);
  55. printArray(arr, n);
  56. }
  57. }
  58.  
  59. int main () {
  60. int arr1[5] = {5, 3, 2, 4, 1};
  61. int arr2[5] = {5, 3, 2, 4, 1};
  62. int arr3[5] = {5, 3, 2, 4, 1};
  63. int n = 5;
  64.  
  65. cout<<"Bubble Sort:"<<endl;
  66. BubbleSort (arr1, n);
  67.  
  68. cout<<endl<<"Insertion Sort:"<<endl;
  69. InsertionSort (arr2, n);
  70.  
  71. cout<<endl<<"Selection Sort:"<<endl;
  72. SelectionSort (arr3, n);
  73.  
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0.01s 5456KB
stdin
Standard input is empty
stdout
Bubble Sort:
Array after 1 iteration: 
3 2 4 1 5 
Array after 2 iteration: 
2 3 1 4 5 
Array after 3 iteration: 
2 1 3 4 5 
Array after 4 iteration: 
1 2 3 4 5 
Array after 5 iteration: 
1 2 3 4 5 

Insertion Sort:
Array after 1 iteration: 
3 5 2 4 1 
Array after 2 iteration: 
2 3 5 4 1 
Array after 3 iteration: 
2 3 4 5 1 
Array after 4 iteration: 
1 2 3 4 5 

Selection Sort:
Array after 1 iteration: 
1 3 2 4 5 
Array after 2 iteration: 
1 2 3 4 5 
Array after 3 iteration: 
1 2 3 4 5 
Array after 4 iteration: 
1 2 3 4 5 
Array after 5 iteration: 
1 2 3 4 5