冒泡排序1
void swap ( vector< int > arr, int i, int j)
{
int temp = arr[ i] ;
arr[ i] = arr[ j] ;
arr[ j] = temp;
}
void bubbleSort1 ( vector< int > arr)
{
for ( int i = 0 ; i < arr. size ( ) - 1 ; i++ )
{
for ( int j = 0 ; j < arr. size ( ) - 1 - i; j++ )
{
if ( arr[ j] > arr[ j + 1 ] )
{
swap ( arr, j, j + 1 ) ;
}
}
}
}
冒泡排序2
void bubbleSort2 ( vector< int > arr)
{
bool swapped = true ;
for ( int i = 0 ; i < arr. size ( ) - 1 ; i++ ) {
if ( ! swapped)
break ;
swapped = false ;
for ( int j = 0 ; j < arr. size ( ) - 1 - i; j++ ) {
if ( arr[ j] > arr[ j + 1 ] ) {
swap ( arr, j, j + 1 ) ;
swapped = true ;
}
}
}
}
冒泡排序3
void bubbleSort3 ( vector< int > arr)
{
bool swapped = true ;
int indexOfLastUnsortedElement = arr. size ( ) - 1 ;
int swappedIndex = - 1 ;
while ( swapped)
{
swapped = false ;
for ( int i = 0 ; i < indexOfLastUnsortedElement; i++ )
{
if ( arr[ i] > arr[ i + 1 ] ) {
swap ( arr, i, i + 1 ) ;
swapped = true ;
swappedIndex = i;
}
}
indexOfLastUnsortedElement = swappedIndex;
}
}