home Tech Library Tech Forum
Publisher
 
Sorting Algorithms        
 
 
Bubble sort
 
 

 

The bubble sort works by comparing each item in the list with the item next to it, and swapping them if required. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items. This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.
Bubble sort is believed to be the oldest and simplest sort in use. But it is also believed to be the most inefficient and slow sorting algorithm.

Example in C++
void bubbleSort(int numbers[], int size)
{
   int i, j, temp;

   for (i = (size - 1); i >= 0; i--)
   {
      for (j = 1; j <= i; j++)
      {
         if (numbers[j-1] > numbers[j])
         {
             temp = numbers[j-1];
             numbers[j-1] = numbers[j];
             numbers[j] = temp;
         }
      }
   }
}


Bubble sort is also known as exchange sort. Bubble sort algorithm works as follows:
1. Compare adjacent elements. If the first element is greater than the second one, then swap them.
2. Repeat the same for each pair of adjacent elements and start with the first two and end with the last two elements.
3. Repeat the cycle for all elements except the last one from the previous cycle.
4. Keep repeating this cycle, until we have no more pairs to compare.
 
   
  RELATED TOPICS  
Bucket Sorting
Radix sort
Insertion sort
Shell sort
Merge sort
Heap sort
Quick sort



 
           
Home | Profile | Users | Library | Publisher | Tech Forum | News | Contact Us