-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort-Bubble.cpp
More file actions
55 lines (47 loc) · 963 Bytes
/
Copy pathSort-Bubble.cpp
File metadata and controls
55 lines (47 loc) · 963 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
54
55
//Optimized solution for bubble sort
//Big O of program-1 is n^2
//if there is no swapping at first iteration, it means that array is already sorted
#include <iostream>
using namespace std;
void swap(int *ptr1, int *ptr2)
{
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}
void sortArray(int arr[], int size)
{
int i,j;
bool swapped = false;
for(i=0 ; i<size-1 ; i++)
{
for(j=0 ; j<size-i-1 ; j++)
{
if(arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
if(!swapped)
{
break;
}
}
}
void printArray(int arr[], int size)
{
for(int i=0 ; i<size ; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main()
{
int arr[] = {1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
printArray(arr,size);
sortArray(arr,size);
printArray(arr,size);
}