Advertisement
skb50bd

Selection Sort Vs. Bubble Sort

May 19th, 2015
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. //Selection Sort
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. void swap (int *p, int *q)
  6. {
  7.     int temp;
  8.  
  9.     temp = *p;
  10.     *p = *q;
  11.     *q = temp;
  12.  
  13.     return;
  14. }
  15.  
  16. int main()
  17. {
  18.     int i, j, n;
  19.  
  20.     cout << "Size of the Array : ";
  21.     cin >> n;
  22.  
  23.     int a[n];
  24.  
  25.     cout << "Elements of the Array : ";
  26.     for (i = 0; i < n; i++)
  27.         cin >> a[i];
  28.  
  29.     for (i = 0; i < n - 1 ; i++)
  30.         for (j = i + 1; j < n; j++)
  31.             if(a[i] > a[j])
  32.                 swap(&a[i], &a[j]);
  33.  
  34.     cout << "Sorted Array : ";
  35.     for (i = 0; i < n; i++)
  36.         cout << a[i] << " ";
  37.  
  38.     cout << endl;
  39.  
  40.     return 0;
  41. }
  42.  
  43.  
  44.  
  45.  
  46. //Bubble Sort
  47. #include <iostream>
  48. using namespace std;
  49.  
  50. void swap (int *p, int *q)
  51. {
  52.     int temp;
  53.  
  54.     temp = *p;
  55.     *p = *q;
  56.     *q = temp;
  57.  
  58.     return;
  59. }
  60.  
  61. int main()
  62. {
  63.     int i, j, n;
  64.  
  65.     cout << "Size of the Array : ";
  66.     cin >> n;
  67.  
  68.     int a[n];
  69.  
  70.     cout << "Elements of the Array : ";
  71.     for (i = 0; i < n; i++)
  72.         cin >> a[i];
  73.  
  74.     for (i = 0; i < n - 1 ; i++)
  75.         for (j = 0; j < (n - 1) - i; j++)
  76.             if(a[j] > a[j + 1])
  77.                 swap(&a[j], &a[j + 1]);
  78.  
  79.     cout << "Sorted Array : ";
  80.     for (i = 0; i < n; i++)
  81.         cout << a[i] << " ";
  82.  
  83.     cout << endl;
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement