Algorithm backup ---- Bubble Sort(冒泡排序算法)

  The bubble sort is the oldest and simplest sort in use. Unfortunately, it's also the slowest.

  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 (in other words, all items are in the correct order). This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.

  The bubble sort is generally considered to be the most inefficient sorting algorithm in common usage. Under best-case conditions (the list is already sorted), the bubble sort can approach a constant O(n) level of complexity. General-case is an abysmal O(n2).

  Pros: Simplicity and ease of implementation.
  Cons: Horribly inefficient.

  Below is source code of the basic bubble sort algorithm:

///   <summary>
///  Bubble sort algorithm
///   </summary>
///   <param name="numbers"> numbers array to be sorted </param>
public   static   void  BubbleSort( int [] numbers)
{
    
int  i, j, temp;
    
int  arraySize  =  numbers.Length;
    
for  (i  =  (arraySize  -   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;
            }
        }
    }
}

  As mentioned above, it will run circulating even the list is already sorted. So I make a little change and add a sign to reduce the time cost of this case.

///   <summary>
///  Bubble sort algorithm
///   </summary>
///   <param name="numbers"> numbers array to be sorted </param>
public   static   void  BubbleSort( int [] numbers)
{
    
int  i, j, temp;
    
int  arraySize  =  numbers.Length;
    
for  (i  =  (arraySize  -   1 ); i  >=   0 ; i -- )
    {
        
// Add a sign tag here
         bool  isChanged  =   false ;
        
for  (j  =   1 ; j  <=  i; j ++ )
        {
            
if  (numbers[j - 1 >  numbers[j])
            {
                temp 
=  numbers[j - 1 ];
                numbers[j
- 1 =  numbers[j];
                numbers[j] 
=  temp;
                isChanged 
=   true ;
            }
        }
        
// If no change, the list is already sorted.
         if  ( ! isChanged)
            
return ;
    }
}
  

Go to my home page for more posts

你可能感兴趣的:(Algorithm)