bubble sort array c++ code example

Example 1: bubble sort in c++

void bubble_sort( int A[ ], int n ) {
    int temp;
    for(int k = 0; k< n-1; k++) {
        // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations

        for(int i = 0; i < n-k-1; i++) {
            if(A[ i ] > A[ i+1] ) {
                // here swapping of positions is being done.
                temp = A[ i ];
                A[ i ] = A[ i+1 ];
                A[ i + 1] = temp;
            }
        }
    }
}

Example 2: array sort c++

#include <iostream>
2 #include <array>
3 #include <string>
4 #include <algorithm>
5
6 using namespace std;
7
8 int main(){
9 array<string, 4> colours = {"blue", "black", "red", "green"};
10 for (string colour : colours){
11 cout << colour << ' ';
12 }
13 cout << endl;
14 sort(colours.begin(), colours.end());
15 for (string colour : colours){
16 cout << colour << ' ';
17 }
18 return 0;
19 }
66
20
21 /*
22 Output:
23 blue black red green
24 black blue green red
25 */

Example 3: code for bubble sort in c++

void bubbleSort (int S[ ],  int length) {
	bool isSorted = false;
	while(!isSorted)
   	{
		isSorted = true;
		for(int i = 0; i<length; i++)
      	{
		     if(S[i] > S[i+1])
           	     {
			int temp = S[i];
			S[i] = S[i+1];
     	       		S[i+1] = temp;
            		isSorted = false;
           	      }
      	}
      	length--;
}
}

Tags:

Cpp Example