Describe bubble sort algorithm and write an example of implementation

Bubble sort, sometimes referred to as sinking sort, is a primitive sorting algorithm that repeatedly steps through the array of elements, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems.

Performance

Bubble sort has worst-case and average complexity both О(n2), where n is the number of items being sorted. There exist many sorting algorithms with substantially better worst-case or average complexity of O(n log n). Even other О(n2) sorting algorithms, such as insertion sort, tend to have better performance than bubble sort. Therefore, bubble sort is not a practical sorting algorithm when n is large.

Example

int[] array= { 89, 76, 45, 92, 67, 12, 99 };
int length = array.Length;
int temp = array[0];
for (int i = 0; i < length; i++)
{
    for (int j = i+1; j < length; j++)
    {
        if (array[i] > array[j])
        {
            temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}

Short answer

  • Bubble sort is a simple sorting algorithm that repeatedly steps through the array of elements, compares each pair of adjacent items and swaps them if they are in the wrong order until array is sorted.
  • Bubble sort has worst-case and average complexity both О(n2), which indicates very poor performance.

Similar articles

Comments