forked from TechVine/DSA--Hacktoberfest-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubbleSort.cpp
47 lines (41 loc) · 1013 Bytes
/
bubbleSort.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
#include <iostream>
using namespace std;
const int N = 1e5+10;
int arr[N];
void swap(int *a, int *b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
void display(int *arr, int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << ' ';
cout << endl ;
}
void bubbleSort(int *arr, int size) {
bool flag = false;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size-i-1; j++) // size-i-1 bcz last element is placed at its correct position
{
display(arr, size);
if (arr[j] > arr[j+1])
{
swap(arr[j], arr[j+1]);
flag = true;
}
}
if (!flag) return;
}
}
int main()
{
int n;
cout << "Enter the size of an array: "; cin >> n;
cout << "Enter " << n << " elements " << endl ;
for (int i = 0; i < n; i++)
cin >> arr[i];
bubbleSort(arr, n);
display(arr, n);
return 0;
}