Custom Search

 

 

 

 
 

 

Bubble Sort


Binary Search | Bubble Sort | Selection Sort | Finding Maximum Value | Linear Search | Celsius to Fahrenheit | 10 Pseudo-random numbers | Calculating Average | Swapping Values | Lowercase/ Uppercase
   
  The bubble sort is one of the simplest sorting algorithms, but not one of the most efficient. It puts a list into increasing order by successively comparing adjacent elements, interchanging them if they are in the wrong order.

Complexity

The bubble sort uses (n-1)n/2 comparisons, so it has (-) (n2) worst-case complexity in terms of the number of comparisons used.

   
 

Algorithm

Procedure BubbleSort (num 1,……num n )

for i = 1 to n - 1

for j = 1 to n - i

if num j > num j+1, then interchange num j  and num j+1


{num j,... num n  is in increasing order}

   
 

C++ Source Code

#include <iostream.h>

int BubbleSort(int [], int);

int main()
{
const int NUMEL = 10;
int nums[NUMEL] = {22,5,67,98,45,32,101,99,73,10};
int i, moves;

moves = BubbleSort(nums, NUMEL);

cout << "The sorted list, in ascending order, is:\n";
for (i = 0; i < NUMEL; ++i)
cout << " " <<nums[i];

cout << '\n' << moves << " were made to sort this list\n";

return 0;
}

int
BubbleSort(int num[], int numel)
{
    int i, j, grade, moves = 0;

   
for ( i = 0; i < (numel - 1); i++)
        {
        
for(j = 1; j < numel; j++)
          {

             if (num[j] < num[j-1])
             {
                    grade = num[j];
                    num[j] = num[j-1];
                    num[j-1] = grade;
                    moves++;
              }
            }
         }

return
moves;
}

 

 
   
 

 

 
 

Disclaimer: Pak/ed and the contributors are not responsible for any errors contained and are not liable for any damages resulting from the use of this material.  Disclaimer

                        

 

 

 

Custom Search
 

Home      Disclaimer      Advertise      Contact      Privacy Policy     

Copyright © 2004-15 Paked.com. All rights reserved.

Note: Site best viewed at 1024 x 768 or higher screen resolution