-
Notifications
You must be signed in to change notification settings - Fork 130
Expand file tree
/
Copy pathbubbleSort.cpp
More file actions
61 lines (56 loc) · 1.18 KB
/
bubbleSort.cpp
File metadata and controls
61 lines (56 loc) · 1.18 KB
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
#include <iostream>
using namespace std;
void printArray(int *arr, int length)
{
for (int i = 0; i < length; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void bubbleSort(int *arr, int length)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void bubbleSortAdaptive(int *arr, int length)
{
int isSorted = 0;
for (int i = 0; i < length - 1; i++)
{
isSorted = 1;
for (int j = 0; j < length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
isSorted = 0;
}
}
if (isSorted)
{
return;
}
}
}
int main()
{
int arr[] = {12, 54, 65, 7, 23, 9};
int length = sizeof(arr) / sizeof(int);
printArray(arr, length);
bubbleSortAdaptive(arr, length);
printArray(arr, length);
return 0;
}