冒泡排序算法实现
public class Sort {
public static void main ( String[ ] args) {
int [ ] arr = { 9 , 8 , 10 , 7 , 6 , 0 , 11 } ;
int swap = 0 ;
int compare = 0 ;
for ( int i = 0 ; i < arr. length - 1 ; i++ ) {
for ( int j = 0 ; j < arr. length - i - 1 ; j++ ) {
compare++ ;
if ( arr[ j] > arr[ j+ 1 ] ) {
int temp;
temp = arr[ j] ;
arr[ j] = arr[ j+ 1 ] ;
arr[ j+ 1 ] = temp;
swap++ ;
}
}
}
System. out. println ( "比较次数:" + compare) ;
System. out. println ( "交换次数:" + swap) ;
for ( int i = 0 ; i < arr. length; i++ ) {
System. out. println ( arr[ i] ) ;
}
}
}
选择排序算法实现
public static void main ( String[ ] args) {
int [ ] arr = { 9 , 8 , 10 , 7 , 6 , 0 , 11 } ;
int compare = 0 ;
int swap = 0 ;
for ( int i = 0 ; i < arr. length - 1 ; i++ ) {
int min = i;
for ( int j = i+ 1 ; j < arr. length ; j++ ) {
compare++ ;
if ( arr[ j] < arr[ min] ) {
min = j;
}
}
if ( min != i) {
int temp;
temp = arr[ min] ;
arr[ min] = arr[ i] ;
arr[ i] = temp;
swap++ ;
}
}
System. out. println ( "比较次数:" + compare) ;
System. out. println ( "交换次数:" + swap) ;
for ( int i = 0 ; i < arr. length; i++ ) {
System. out. println ( arr[ i] ) ;
}
}