• API
• FAQ
• Tools
• Archive
SHARE
TWEET # Untitled a guest Nov 19th, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. // File testSort.Incomplete.cpp
2.
3. // algorithm: bubbleSort
4.
5. /* 1. In a sorted list in ascending order:
6.
7.         If i < j then a[i] <= a[j], for any i, j, indexes of the array
8.
9.     2. In a sorted list in ascending order:
10.
11.         (2) for all values of i, a[i] <= a[i + 1].
12.
13.     3. We could put in order the array by taking pairs where (2) is not true
14.
15.         we switch the values so (2) becomes true
16.
17.     4. Step 3 is done by making i = 0, 1, 2, ... size - 2, making the switch if
18.
19.         (2) is not true
20.
21.     5. Step 4 is done until making i = 0, 1, 2, ... size - 2, no switch  is done,
22.
23.         i.e., (2) becomes true, te sort is done.
24.
25. */
26. #include <iostream>
27. void sort (int x[], int size);
28. using namespace std;
29. int main ()
30. {
31.     const int size = 20;
32.     int a[size];
33.     a = 1;
34.     a = 2;
35.     a = 3;
36.     cout << "\nBefore Sort  " << a << " " << a << " " << a << endl;
37.
38.     sort (a, 3);
39.
40.     cout << "\nAfter Sort  " << a << " " << a << " " << a << endl;
41.
42.     a = 3;
43.     a = 2;
44.     a = 1;
45.
46.     cout << "\nBefore Sort  " << a << " " << a << " " << a << endl;
47.
48.     sort (a, 3);
49.
50.     cout << "\nAfter Sort  " << a << " " << a << " " << a << endl;
51.
52.     a = 20;
53.     a = 30;
54.     a = -50;
55.
56.     cout << "\nBefore Sort  " << a << " " << a << " " << a << endl;
57.
58.     sort (a, 3);
59.
60.     cout << "\nAfter Sort  " << a << " " << a << " " << a << endl;
61.
62. }
63. int temp;
64. void swap(int *xp, int *yp)
65. {
66.     int temp = *xp;
67.     *xp = *yp;
68.     *yp = temp;
69. }
70. void sort(int arr[], int n)
71. {
72.    int i, j;
73.    bool swapped;
74.    for (i = 0; i < n-1; i++)
75.    {
76.      swapped = false;
77.      for (j = 0; j < n-i-1; j++)
78.      {
79.         if (arr[j] > arr[j+1])
80.         {
81.            swap(&arr[j], &arr[j+1]);
82.            swapped = true;
83.         }
84.      }
85.
86.      // IF no two elements were swapped by inner loop, then break
87.      if (swapped == false)
88.         break;
89.    }
90. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top