Use the Bubble sort sorting algorithm to sort an array of integers, with c plus plus
Bubble sort is a simple sorting algorithm. Its operation is very simple: each pair of adjacent elements of the list is compared and if they are in the wrong order are reversed position. The Bubble sort is not an efficient algorithm! And should be used only for educational purposes. The following sample code:
#include <iostream>
int main (int argc, char *argv[])
{
// Initialize random number generator
srand(time(NULL));
// Define the length of the array
const int LENGHT = 7;
// Create an array of LENGTH elements
int v[LENGHT];
// Fill the array with random integers
for (int i=0; i<LENGHT; i++) v[i] = (rand()%100)+1;
// Showing the contents of the array
printf("The contents of the original array\n");
for (int i=0; i<LENGHT; i++) printf("%d " , v[i]);
printf("\n\n");
// Sort the array
int i,j;
int temp = 0;
for(i=1; i<LENGHT; i++)
{
for(j=LENGHT-1; j>=i; j--)
{
if(v[j-1]>v[j])
{
// Swap the elements
temp = v[j-1];
v[j-1] = v[j];
v[j] = temp;
//Display current order of items
printf("\n");
for (int i=0; i<LENGHT; i++) printf("%d " , v[i]);
}
}
}
printf("\n\n");
// Showing the contents of the array sorted
printf("The contents of the array sorted\n");
for (int i=0; i<LENGHT; i++) printf("%d " , v[i]);
return 0;
}
This is the result:
The contents of the original array
53 79 23 49 2 45 47
53 79 23 2 49 45 47
53 79 2 23 49 45 47
53 2 79 23 49 45 47
2 53 79 23 49 45 47
2 53 79 23 45 49 47
2 53 23 79 45 49 47
2 23 53 79 45 49 47
2 23 53 79 45 47 49
2 23 53 45 79 47 49
2 23 45 53 79 47 49
2 23 45 53 47 79 49
2 23 45 47 53 79 49
2 23 45 47 53 49 79
2 23 45 47 49 53 79
The contents of the array sorted
2 23 45 47 49 53 79