Skip to content

Commit 48a0661

Browse files
committed
added bubble sort algorithm
1 parent 6e8c53b commit 48a0661

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

bubble.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
5+
void swap(int *xp, int *yp)
6+
{
7+
int temp = *xp;
8+
*xp = *yp;
9+
*yp = temp;
10+
}
11+
12+
// A function to implement bubble sort
13+
void bubbleSort(int arr[], int n)
14+
{
15+
int i, j;
16+
for (i = 0; i < n-1; i++)
17+
18+
// Last i elements are already in place
19+
for (j = 0; j < n-i-1; j++)
20+
if (arr[j] > arr[j+1])
21+
swap(&arr[j], &arr[j+1]);
22+
}
23+
24+
/* Function to print an array */
25+
void printArray(int arr[], int size)
26+
{
27+
int i;
28+
for (i=0; i < size; i++)
29+
cout<<arr[i];
30+
cout<<"\n";
31+
}
32+
33+
// Driver program to test above functions
34+
int main()
35+
{
36+
int arr[] = {64, 34, 25, 12, 22, 11, 90};
37+
int n = sizeof(arr)/sizeof(arr[0]);
38+
bubbleSort(arr, n);
39+
cout<< "Sorted array: \n";
40+
printArray(arr, n);
41+
return 0;
42+
}

0 commit comments

Comments
 (0)