package com. mypackage. array ; import java. util. Arrays ; public class Demo07 { public static void main ( String [ ] args) { int [ ] a = { 3 , 2 , 6 , 7 , 4 , 5 , 6 , 34 , 56 , 7 } ; int [ ] sort1 = sort1 ( a) ; System . out. println ( Arrays . toString ( sort1) ) ; int [ ] sort2 = sort2 ( a) ; System . out. println ( Arrays . toString ( sort2) ) ; } public static int [ ] sort1 ( int [ ] array) { int temp = 0 ; for ( int i = 0 ; i < array. length- 1 ; i++ ) { for ( int j = 0 ; j < array. length- 1 - i; j++ ) { if ( array[ j+ 1 ] > array[ j] ) { temp = array[ j] ; array[ j] = array[ j+ 1 ] ; array[ j+ 1 ] = temp; } } } return array; } public static int [ ] sort2 ( int [ ] array) { int temp = 0 ; for ( int i = 0 ; i < array. length- 1 ; i++ ) { for ( int j = 0 ; j < array. length- 1 - i; j++ ) { if ( array[ j+ 1 ] < array[ j] ) { temp = array[ j] ; array[ j] = array[ j+ 1 ] ; array[ j+ 1 ] = temp; } } } return array; }
}
优化程序,减少不必要的循环次数:
public static int [ ] sort3 ( int [ ] array) { int temp = 0 ; for ( int i = 0 ; i < array. length- 1 ; i++ ) { boolean flag = false ; for ( int j = 0 ; j < array. length- 1 - i; j++ ) { if ( array[ j+ 1 ] < array[ j] ) { temp = array[ j] ; array[ j] = array[ j+ 1 ] ; array[ j+ 1 ] = temp; flag = true ; } } if ( flag == false ) { break ; } } return array;
}