Bubble Sort Algorithm
One of the most famous sort algorithm in computer science is the Bubble Sort, it consist of an iterator through list element doing swaps untill all element have been sorted.
The bubble sort algorithm is really simple to code but impractical to use in case when large amount of data are invoved. The average worst case performance is O(n^2) and its best is O(n) and only happens with small amount of data.
There are a plenty of sort algorithms more complex but faster than the Bubble, to cite some we have: QuickSort, MergeSort, Insertion Sort and Selection Sort and others.
Here I give you an example of this algorithm using C# but you can implement with any programming language:
public class SortAlgorithmsByEdgar<T> where T : IComparable<T>
{
public void SortBubble(T[] array)
{
if (array != null)
{
bool swaped = true;
do
{
swaped = false;
for (int count = 1; count < array.Length; count++)
{
if (array[count - 1].CompareTo(array[count]) > 0)
{
Swap(array, count - 1, count);
swaped = true;
}
}
} while (swaped);
}
}
private void Swap(T[] array, int left, int right)
{
if (left != right)
{
T temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
}
Here you can see the most used sorting algorithms: https://github.com/edgarleonardo/SortAlgorithms
The bubble sort algorithm is really simple to code but impractical to use in case when large amount of data are invoved. The average worst case performance is O(n^2) and its best is O(n) and only happens with small amount of data.
There are a plenty of sort algorithms more complex but faster than the Bubble, to cite some we have: QuickSort, MergeSort, Insertion Sort and Selection Sort and others.
Here I give you an example of this algorithm using C# but you can implement with any programming language:
public class SortAlgorithmsByEdgar<T> where T : IComparable<T>
{
public void SortBubble(T[] array)
{
if (array != null)
{
bool swaped = true;
do
{
swaped = false;
for (int count = 1; count < array.Length; count++)
{
if (array[count - 1].CompareTo(array[count]) > 0)
{
Swap(array, count - 1, count);
swaped = true;
}
}
} while (swaped);
}
}
private void Swap(T[] array, int left, int right)
{
if (left != right)
{
T temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
}
Here you can see the most used sorting algorithms: https://github.com/edgarleonardo/SortAlgorithms
Comments
Post a Comment