冒泡思想:
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在 这一点,最后的元素应该会是最大的数。
针对所有的元素重复以上的步骤,除了最后一个。
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
优化冒泡:
package Data. Structure. sort. exchangeSort;
import java. util. Arrays;
public class BubbleSort {
public static void main ( String[ ] args) {
int A[ ] = { 3 , 9 , - 1 , 10 , 20 } ;
BubbleSort2 ( A) ;
for ( int i = 0 ; i < A. length; i++ ) {
System. out. println ( A[ i] ) ;
}
}
public static void BubbleSort1 ( int A[ ] ) {
int temp;
for ( int i = 0 ; i < A. length - 1 ; i++ ) {
int flag = 0 ;
for ( int j = 0 ; j < A. length - 1 - i; j++ ) {
if ( A[ j] > A[ j + 1 ] ) {
temp = A[ j] ;
A[ j] = A[ j + 1 ] ;
A[ j + 1 ] = temp;
flag = 1 ;
}
}
System. out. println ( "第" + ( i + 1 ) + "趟排序的结果:" ) ;
System. out. println ( Arrays. toString ( A) ) ;
if ( flag == 0 ) {
return ;
}
}
}
public static void BubbleSort2 ( int A[ ] ) {
int temp;
for ( int i = 0 ; i < A. length - 1 ; i++ ) {
int flag = 0 ;
for ( int j = A. length- 1 ; j > i; j-- ) {
if ( A[ j- 1 ] > A[ j] ) {
temp = A[ j] ;
A[ j] = A[ j - 1 ] ;
A[ j - 1 ] = temp;
flag = 1 ;
}
}
if ( flag == 0 ) {
return ;
}
}
}
}
结束语:
路漫漫其修远兮 吾将上下而求索