Bubbe Sort and Selection Sort in C#

ddanbe 0 Tallied Votes 836 Views Share

Although there is little need for any sort algorithm in C#. Every collection class has a sort method, so why would you wanna write one for yourself? My guess to learn and see how it is done. Well her are implementations of two popular sorts. The arrays are integer but you can change the type if you want.

//sort the items of an array using straight insertion sort        
//        
static void StraightInsertionSort(int[] listtosort)        
{            
    int element;            
    int ic;     
    //index of element to be compared, index starts at 0             
    for (int loopvar = 1; loopvar < listtosort.Length; loopvar++)  //loop trough each element in turn            
    {                
        element = listtosort[loopvar];                
        ic = loopvar-1;                
        while (ic >= 0 && listtosort[ic] > element )                 
        {                    
            listtosort[ic + 1] = listtosort[ic];    //move all elements                    
            ic--;                
        }                
        listtosort[ic + 1] = element;    //Insert element            
    }                   
}          

// sort the items of an array using bubble sort         
//        
public static void BubbleSort( int[] ar )              
{                     
    for ( int pass = 1; pass < ar.Length; pass++ )                            
        for ( int i = 0; i < ar.Length - 1; i++ )                                   
            if ( ar[ i ] > ar[ i + 1 ] )                                         
                Swap( ar, i );              
}                

// swap two items of an array        
//        
public static void Swap( int[] ar, int first )              
{                     
    int hold;                      
    hold = ar[ first ];                     
    ar[ first ] = ar[ first + 1 ];                     
    ar[ first + 1 ] = hold;              
}
subtercosm 0 Light Poster

Popular to implement... But unpopular to use :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.