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++) {
for(int i = 0; i < n-k-1; i++) {
if(A[ i ] > A[ i+1] ) {
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
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--;
}
}