1void bubble_sort( int A[ ], int n ) {
2 int temp;
3 for(int k = 0; k< n-1; k++) {
4 // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations
5
6 for(int i = 0; i < n-k-1; i++) {
7 if(A[ i ] > A[ i+1] ) {
8 // here swapping of positions is being done.
9 temp = A[ i ];
10 A[ i ] = A[ i+1 ];
11 A[ i + 1] = temp;
12 }
13 }
14 }
15}
1/* Bubble sort code in C++ */
2#include <bits/stdc++.h>
3using namespace std;
4int main (void) {
5 int a[] = {5, 4, 3, 2, 1}, tempArr, i, j;
6 for (i = 0; i < 5; i++) {
7 for (j = i + 1; j < 5; j++) {
8 if (a[j] < a[i]) {
9 tempArr = a[i];
10 a[i] = a[j];
11 a[j] = tempArr;
12 }
13 }
14 }
15 for(i = 0; i < 5; i++) {
16 cout<<a[i]<<"\n";
17 }
18 return 0;
19}
1void bubbleSort (int S[ ], int length) {
2 bool isSorted = false;
3 while(!isSorted)
4 {
5 isSorted = true;
6 for(int i = 0; i<length; i++)
7 {
8 if(S[i] > S[i+1])
9 {
10 int temp = S[i];
11 S[i] = S[i+1];
12 S[i+1] = temp;
13 isSorted = false;
14 }
15 }
16 length--;
17}
18}
19
1// template <class t>
2// void bubble <t>::sort(int n)
3template < typename T > void bubble_sort( T a[], int n )
4{
5 int i,j;
6 //t temp;
7 T temp ;
8 for(i=0; i<n; i++)
9 {
10 for(j=i+1; j<n; j++)
11 {
12 if(a[i]>a[j]) //bubble sort algo
13 {
14 temp=a[i];
15 a[i]=a[j];
16 a[j]=temp;
17 }
18 }
19 }
20}
21
1void bubbleSort(int arr[], int size){
2 int temp = int();
3 //print out the unsorted values
4 for ( int i = 0; i < size -1; i ++)
5 cout << arr[i] << "\t";
6 cout << endl << endl;
7
8
9 for (int i = 1; i < size; i++ ){
10 for(int j = 0; j < size - i ; j ++){//size-i is the sorted part of the array
11 if( arr[j] > arr[j + 1]){//if the value is greater than the next value in the array, swap it
12 temp = arr[j];
13 arr[j] = arr[j+1];//swap the two values
14 arr[j+1] = temp;
15
16 }//end if
17 }//end for
18 }//end for
19
20}//end bubbleSort