冒泡排序
int [ ] arr = { 5 ,2 ,3 ,1 } ;
for ( int i = 0 ; i < arr. length - 1 ; i++ ) {
for ( int j = 0 ; i < arr. length- i- 1 ; j++ ) {
if ( arr[ j] > arr[ j+ 1 ] ) {
int temp = arr[ i+ 1 ] ;
arr[ j+ 1 ] = arr[ i] ;
arr[ j] = temp; } }
}
system. out. println ( Arrays . toString ( arr) ) ;
选择排序
int [ ] arr = { 5 ,2 ,3 ,1 } ;
for ( int i = 0 ; i < arr. length - 1 ; i++ ) {
for ( int j = i + 1 ; i < arr. length; j++ ) {
if ( arr[ i] > arr[ j] ) {
int temp = arr[ i] ;
arr[ i] = arr[ j] ;
arr[ j] = temp; } }
}
system. out. println ( Arrays . toString ( arr) ) ;
简化代码,适用于当数组非常大时提高性能
int [ ] arr = { 5 ,1 ,3 ,2 } ; / /
for ( int i = 0 ; i < arr. length - 1 ; i++ ) { int minIndex = i;
for ( int j = i + 1 ; j < arr. length; j++ ) {
if ( arr[ minIndex] > arr[ i] ) {
minIndex = j; }
}
if ( i != minIndex) {
int temp = arr[ i] ;
arr[ i] = arr[ minIndex] ;
arr[ minIndex] = temp; }
}
system. out. println ( Arrays . toString ( arr) ) ;
二分查找
public static void main ( String [ ] args) { int [ ] arr = { 7 , 23 , 79 , 81 , 103 , 127 , 131 , 147 } ; System . out. println ( binarySearch ( arr, 81 ) ) ; System . out. println ( binarySearch ( arr, 166 ) ) ; } public static int binarySearch ( int [ ] arr, int data) { int left = 0 ; int right = arr. length- 1 ; while ( left <= right) { int middle = ( left + right) / 2 ; if ( data < arr[ middle] ) { right = middle - 1 ; } else if ( data > arr[ middle] ) { left = middle + 1 ; } else { return middle; } } return - 1 ; }