"Data Structure: Deng Junhui Edition" - Bubble Sort

1, ideas

Each time a comparison between two adjacent numbers;

After each round of the comparison always filter out the maximum number or minimum number.

2, source

#include <memory> 

void BubbleSort (szArray int [], int nLen); 

void main () 
{ 
	int szArray [] = {6,4,8,1,9,13}; 
	BubbleSort (szArray, _countof (szArray)); 
	getchar (); 
} 

Void BubbleSort (szArray int [], int nLen) 
{ 
	int NTMP = 0; 
	for (int j = 0; j <nLen - 1; j ++) 
	{ 
		for (int i = 0; i <nLen - j - 2; i ++) 
		{ 
			if (szArray [i]> szArray [i + 1]) 
			{ 
				NTMP szArray = [i + 1]; 
				szArray [i + 1] = szArray [i]; 
				szArray [i] = N tmp; 
			} 
		} 
	} 

	Printf ( "line"); 
	for (int i = 0; i <nLen; i ++)  
	{
		printf ( "% d", szArray [i]);
	}
	printf("\n");
}

 3, optimization

If you find a cycle have all been ordered, then go no further circulation.

void OptBubbleSort ( int szArray [], int nLen) 
{ 
    int NTMP = 0 ;
    int nTmpLen = nLen; 
    BOOL bSorted = FALSE; 

    while (! bSorted) 
    { 
        bSorted = TRUE;
        for ( int i = 0 ; i <nTmpLen - 2 ; i ++ ) 
        { 
            if (szArray [i]> szArray [i + 1 ]) 
            { 
                NTMP = szArray [i + 1 ];
                szArray[i + 1] = szArray[i];
                szArray[i] = nTmp;
                bSorted = FALSE;
            }
        }
        nTmpLen--;
    }

    printf("Sorted:");
    for (int i = 0; i < nLen; i++)
    {
        printf(" %d ", szArray[i]);
    }
    printf("\n");
}

3, the time complexity analysis

Under ideal state is O (n), the average state is O (n ^ 2)

 

Guess you like

Origin www.cnblogs.com/predator-wang/p/11756561.html