public class BubbleSort {
public void sort ( int [ ] A) {
for ( int i = 0 ; i < A. length; i++ ) {
for ( int j = A. length - 1 ; j > i; j-- ) {
if ( A[ j] < A[ j - 1 ] ) {
int temp = A[ j - 1 ] ;
A[ j - 1 ] = A[ j] ;
A[ j] = temp;
}
}
}
}
public static void main ( String args[ ] ) {
int [ ] A = new int [ ] { 3 , 2 , 0 , 5 , 1 , 4 , 9 , 7 , 8 , 6 } ;
BubbleSort bubbleSort = new BubbleSort ( ) ;
bubbleSort. sort ( A) ;
for ( int i = 0 ; i < A. length; i++ ) {
System. out. print ( A[ i] ) ;
}
}
}
public class BubbleSort {
public void sort ( int [ ] A) {
for ( int i = 1 ; i <= A. length; i++ ) {
for ( int j = 0 ; j < A. length - i; j++ ) {
if ( A[ j] > A[ j + 1 ] ) {
int temp = A[ j + 1 ] ;
A[ j + 1 ] = A[ j] ;
A[ j] = temp;
}
}
}
}
public static void main ( String args[ ] ) {
int [ ] A = new int [ ] { 3 , 2 , 0 , 5 , 1 , 4 , 9 , 7 , 8 , 6 } ;
BubbleSort bubbleSort = new BubbleSort ( ) ;
bubbleSort. sort ( A) ;
for ( int i = 0 ; i < A. length; i++ ) {
System. out. print ( A[ i] ) ;
}
}
}
public void sort ( int [ ] A) {
for ( int i = 0 ; i < A. length; i++ ) {
boolean flag = false ;
for ( int j = A. length - 1 ; j > i; j-- ) {
if ( A[ j] < A[ j - 1 ] ) {
int temp = A[ j - 1 ] ;
A[ j - 1 ] = A[ j] ;
A[ j] = temp;
flag = true ;
}
}
if ( ! flag) return ;
}
}
空间复杂度: O ( 1 )
时间复杂度:
最好:有序时, 第一趟就没发生交换flag= false , O ( n)
平均:O ( n^ 2 )
最坏:逆序时, 比较( n- 1 ) + ( n- 2 ) + . . . +1 = O ( n^ 2 ) , 移动= 3 * 比较次数= O ( n^ 2 ) , O ( n^ 2 )
稳定性:稳定