01-16-201107:07 AM
So, what is the Bubble sort algoriithm? The Bubble sort algorithm is a simple sorting algorithm. It will put an array of numbers from least to greatest or vise versa.
The algorithm works by going down the array and compares the numbers individually with each other.
Say your comparing 2, 9, 4, 7, and 5. The Bubble sort compares 9 and 2, then switches. 2, 9, 4, 7, 5
Now it compares 2 and 9. Two is smaller so nothing happens.
Then it compares 9 and 4./ 2, 4, 9, 7, 5
Now it compares 9 and 7 then 9 and 5./ 2, 4, 7, 5, 9
It repeats the process until everything is correct.
You can see this isn't efficient for large arrays.
[code]
//Bubble sort example by Scorch
#include <iostream>
void BubbleSort(int array[], int length)
{
for(int i=0;i<length;++i)
{
for(int j=length;j>i;--j)
{
if(array[i]>array[j])
{
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
std::cout<<array[i]<<"\n";
}
}
int main()
{
int array[] = {9, 4, 12, 134, 26, 19, 47, 94, 668, 1002};
int length = sizeof(array)/sizeof(array[0]);
BubbleSort(array, length);
return 0;
}
[/code]
This will print from least to greatest. If you want the reverse change this line to.
[code]
for(int j=length;j>i;--j) Least to greatest
for(int j=0;j<i;++j) Greatest to least
[/code]
Do remember the Bubblesort is simple, but slow. For large arrays the Insertion sort algorithm is much more efficient.
The algorithm works by going down the array and compares the numbers individually with each other.
Say your comparing 2, 9, 4, 7, and 5. The Bubble sort compares 9 and 2, then switches. 2, 9, 4, 7, 5
Now it compares 2 and 9. Two is smaller so nothing happens.
Then it compares 9 and 4./ 2, 4, 9, 7, 5
Now it compares 9 and 7 then 9 and 5./ 2, 4, 7, 5, 9
It repeats the process until everything is correct.
You can see this isn't efficient for large arrays.
[code]
//Bubble sort example by Scorch
#include <iostream>
void BubbleSort(int array[], int length)
{
for(int i=0;i<length;++i)
{
for(int j=length;j>i;--j)
{
if(array[i]>array[j])
{
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
std::cout<<array[i]<<"\n";
}
}
int main()
{
int array[] = {9, 4, 12, 134, 26, 19, 47, 94, 668, 1002};
int length = sizeof(array)/sizeof(array[0]);
BubbleSort(array, length);
return 0;
}
[/code]
This will print from least to greatest. If you want the reverse change this line to.
[code]
for(int j=length;j>i;--j) Least to greatest
for(int j=0;j<i;++j) Greatest to least
[/code]
Do remember the Bubblesort is simple, but slow. For large arrays the Insertion sort algorithm is much more efficient.