Skip to content

Commit 7ddfb65

Browse files
committed
Add bubble sort algorithm. Add .gitignore
1 parent 65c2716 commit 7ddfb65

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

.gitignore

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
### C++ template
3+
# Prerequisites
4+
*.d
5+
6+
# Compiled Object files
7+
*.slo
8+
*.lo
9+
*.o
10+
*.obj
11+
12+
# Precompiled Headers
13+
*.gch
14+
*.pch
15+
16+
# Compiled Dynamic libraries
17+
*.so
18+
*.dylib
19+
*.dll
20+
21+
# Fortran module files
22+
*.mod
23+
*.smod
24+
25+
# Compiled Static libraries
26+
*.lai
27+
*.la
28+
*.a
29+
*.lib
30+
31+
# Executables
32+
*.exe
33+
*.out
34+
*.app
35+

sorting-algorithms/bubble_sort.cpp

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
void swap(int *xp, int *yp)
2+
{
3+
int temp = *xp;
4+
*xp = *yp;
5+
*yp = temp;
6+
}
7+
8+
9+
void bubbleSort(int[] a)
10+
/*
11+
Bubble sort, sometimes referred to as sinking sort, is a simple sorting
12+
algorithm that repeatedly steps through the list, compares adjacent elements,
13+
and swaps them if they are in the wrong order. The pass through the list is
14+
repeated until the list is sorted.
15+
*/
16+
{
17+
int n = a.length;
18+
for (int j = 0; j < n - 1; ++j){111
19+
for (int i = 0; i < n - j - 1; ++i)
20+
if (a[i] > a[i+1])
21+
swap(a, i, i+1);
22+
}
23+
}
24+
25+
26+
void printArray(int arr[], int size)
27+
{
28+
int i;
29+
for (i = 0; i < size; i++)
30+
std::cout << arr[i] << " ";
31+
std::cout << std::endl;
32+
}
33+
34+
35+
int main()
36+
{
37+
// a main function that can be used to test our code
38+
39+
int arr[] = {1, 5, 6, 3, 2};
40+
41+
bubbleSort(arr);
42+
43+
std::cout << "Sorted array:" << std::endl;
44+
printArray(arr, n);
45+
return 0;
46+
}

0 commit comments

Comments
 (0)