原创老师链接
数组的算法
升序,引入一个工具
使用工具
sort方法
帮我们把数组进行升序,由小到大 会影响数组内部的结构 用法
参考代码
import java. util. Arrays;
public class Test {
public static void main ( String[ ] args) {
int [ ] nums = new int [ ] { 2 , 5 , 3 , 2 , 6 } ;
Arrays. sort ( nums) ;
for ( int i= 0 ; i< nums. length; i++ ) {
System. out. println ( nums[ i] ) ;
}
}
}
交换两个变量
使用第三个变量
import java. util. Arrays;
public class Test {
public static void main ( String[ ] args) {
int a = 11 ;
int b = 22 ;
int temp;
System. out. println ( "数据交换前a与b的值" + a + "---" + b) ;
temp = b;
b = a;
a = temp;
System. out. println ( "数据交换后a与b的值" + a + "---" + b) ;
}
}
temp = b;
b = a;
a = temp;
不允许使用第三个变量
a= a+ b;
b= a- b;
a= a- b;
光标移动的最大下标算法
数组会在哪里停下,取决于数组的长度。 如果数组的长度是n,那么 下标不会走到n/2
算法代码
public class Test {
public static void main ( String[ ] args) {
String[ ] strList = { "a" , "b" , "c" , "d" , "e" , "f" , "g" , "h" , "i" , "j" , "k" } ;
int topIdx = strList. length / 2 ;
for ( int i = 0 ; i < topIdx; i++ ) {
String temp = strList[ i] ;
int changeIndex = strList. length - 1 - i;
strList[ i] = strList[ changeIndex] ;
strList[ changeIndex] = temp;
}
for ( int j = 0 ; j < strList. length; j++ ) {
System. out. print ( strList[ j] ) ;
}
}
}
求最大值
算法
来一个临时变量 让数组成员的值与临时变量比较 谁大,就把谁的值赋给临时变量
代码
public class getmaxnum {
public static void main ( String[ ] args) {
int [ ] numList = { 11 , 22 , 4 , 3 , 55 , 33 } ;
int temp = numList[ 0 ] ;
for ( int i = 1 ; i < numList. length; i++ ) {
if ( numList[ i] > temp) {
temp = numList[ i] ;
}
}
System. out. println ( "最大的值是" + temp) ;
}
}
追加数据
算法
遍历数组找到第一个出现null的位置 记录这个位置,并往数组的这个位置插入数据
代码
String[ ] strList = new String [ 5 ] ;
strList[ 0 ] = "hello" ;
strList[ 1 ] = "java" ;
strList[ 2 ] = "welcom" ;
String sendKey = "c#" ;
for ( int i = 0 ; i < strList. length; i++ ) {
System. out. println ( i) ;
if ( strList[ i] == null) {
strList[ i] = sendKey;
break ;
}
}
for ( int j = 0 ; j < strList. length; j++ ) {
System. out. println ( strList[ j] ) ;
}
中部插入数据
伪代码
第一步:
找到最大有效数据的下标
int temp= 0 ;
for ( int m= 0 ; m< 数组. length; m++ ) {
if ( 数组[ m] == null) {
temp = m;
break ;
}
temp-- ;
}
第二步:后移
for ( int i= temp; i> j; i-- ) {
数组[ i+ 1 ] = 数组[ i] ;
}
第三步:
数据的插入
数组[ j] = “html";