-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSort.cpp
54 lines (54 loc) · 953 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
48
49
50
51
52
53
54
#include<iostream>
using namespace std;
void swap_num(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void display(int *arr, int s)
{
for(int i=0; i<s; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
void bubbleSort(int *arr, int s)
{
for(int i=0; i<s; i++)
{
int swaps=0;
for(int j=0; j<s-i-1; j++)
{
if(arr[j]>arr[j+1])
{
swap_num(arr[j], arr[j+1]);
swaps=1;
}
}
if(!swaps)
{
break;
}
}
}
int main()
{
int n;
cout<<"\nEnter the number of elements:"<<endl;
cin>>n;
int arr[n];
cout<<"\nEnter elements: "<<endl;
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"\nArray before sorting was: "<<endl;
display(arr, n);
bubbleSort(arr, n);
cout<<"\nArray after sorting is: "<<endl;
display(arr, n);
return 0;
}