-
Notifications
You must be signed in to change notification settings - Fork 0
/
15_Bubble-Sort.cpp
executable file
·65 lines (58 loc) · 1.37 KB
/
15_Bubble-Sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
void BubbleSortBestCase(int arr[], int n)
{
for (int i = n - 1; i > 0; i--)
{
bool swapped = 0;
for (int j = 0; j < i; j++)
{
if (arr[j] > arr[j + 1])
{
swapped = 1;
swap(arr[j], arr[j + 1]);
}
}
if (swapped == 0)
break;
}
}
void BubbleSortWorstCase(int arr[], int n)
{
for (int i = n - 1; i > 0; i--) // for(int i=n-2; i>0; i--)
{
for (int j = 0; j < i; j++) // for(int j=0; j<=i; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
}
void PrintArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int arr[100];
int n;
cout << "Enter the size of array: ";
cin >> n;
cout << "Enter the element in array: ";
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "Array before sorting: ";
PrintArray(arr, n);
cout << endl;
cout << "Array after sorting: ";
// BubbleSortBestCase(arr, n); //If we want to best case time complexity.
BubbleSortWorstCase(arr, n); // If we want to worst case time complexity.
PrintArray(arr, n);
}