-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEx0103_BubbleSort.cpp
More file actions
53 lines (44 loc) · 968 Bytes
/
Ex0103_BubbleSort.cpp
File metadata and controls
53 lines (44 loc) · 968 Bytes
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
#include <iostream>
using namespace std;
bool CheckSorted(int* arr, int size)
{
for (int i = 0; i < size - 1; i++)
{
if (arr[i] > arr[i + 1])
return false;
}
return true;
}
void Print(int* arr, int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
//int arr[] = { 5, 1, 4, 2, 8 }; // 위키피디아 예시
int arr[] = { 5, 4, 3, 2, 1 }; // Worst Case
//int arr[] = { 1, 2, 3, 5, 4 }; // Best Case
int n = sizeof(arr) / sizeof(arr[0]);
Print(arr, n);
cout << endl;
// Bubble Sort
{
for (int i = 0; i < n -1; i++)
{
bool swaped = false;
swaped = CheckSorted(arr,n);
if (swaped) break;
for (int j = 0; j < n - i- 1 ; j++)
{
if(arr[j] > arr[j+1]) swap(arr[j], arr[j+1]);
}
Print(arr, n);
}
}
Print(arr, n);
cout << endl;
// Best case
// Stability
}