找出数组中的最大值:
//找出最大值,最小值(思想就是先假设一个最值。然后进行比较)
public static int[] arraysmax(int [] b){
int max=b[0];
for(int i=0;i<b.length;i++){
if(b[i]>max){
max=b[i];
}
}
System.out.println("最大值为:"+max);
return b;
}
public static int[] arraysmin(int [] b){
int min=b[0];
for(int i=0;i<b.length;i++){
if(b[i]<min){
min=b[i];
}
}
System.out.println("最小值为:"+min);
return b;
}
数组的冒泡排序:
public static int[] arr(int [] a){
for(int i=1;i<a.length;i++){
for(int j=0;j<a.length-i;j++){
if(a[j]<a[j+1]){
int temp;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("排序后的数组");
// for(int k=0;k<a.length;k++){
// System.out.println(a[k]);
// }
System.out.println(Arrays.toString(a));
return a;
}
冒泡的优点是:由用户规定排序的方式。
sort排序:
int [] a={1000,2200,3,4,550,30,4,4,30};
//进行sort排序 sort将.....排序 数组 Arrays类有sort
Arrays.sort(a);//只能是由小到大排序
缺点是:只能是由小到大排序
有点是:不用单独定义函数,只需要引用就可以了
数组的转置:
- 转置就是颠倒。
//数组的转置
public static int[] reverse(int [] a){
//转置的部分函数 就是反转
for(int i=0;i<a.length/2;i++){
int temp;//定义中间的变量
temp=a[i];
a[i]=a[a.length-i-1];
a[a.length-1-i]=temp;
}
//转置后的数组 函数的数组循环遍历最好写在函数里 ,不用改变参数的名称,写在主函数 里需要改变参数的名臣
System.out.println("转置的数组:");
for(int n=0;n<a.length;n++){
System.out.print(a[n]+" ");
}
return a;
}
}
- 注意:只能是a.length/2。
数组的复制:
public class ArrayTest {
public static void main(String[] args) {
int a [] = {1,10,15,20,35,80};
int b[] = new int[4];//分配了长度是4的空间,但是没有赋值
// System.arraycopy(src, srcPos, dest, destPos, length)
//src: 源数组
//srcPos: 从源数组复制数据的启始位置
//dest: 目标数组
//destPos: 复制到目标数组的启始位置
//length: 复制的长度
System.arraycopy(a, 0, b, 0, 4);
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
}
}
多个数组的拼接:
public class PingJie {
public static void main(String[] args) {
int [] a={1,2,3,4,5};
int [] b={6,7,8,9,10};
pinJie(a,b);
}
public static int[] pinJie( int [] a,int [] b){
int [] c=new int[a.length+b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
for(int i=0;i<c.length;i++){
System.out.print(c[i]+" ");
}
return c;
}
}
数组的查找:
使用binarySearch进行查找之前,必须使用sort进行排序
如果数组中有多个相同的元素,查找结果是不确定的
public class ArrayTest {
public static void main(String[] args) {
int a[] = new int[] { 10, 60, 65, 81, 35, 8 };
//进行sort排序
Arrays.sort(a);
System.out.println(Arrays.toString(a)); // [8, 10, 35, 60, 65, 81]
// index是进过sort排序后的位置
System.out.println("数组中 60 出现的位置:"+Arrays.binarySearch(a, 60));
}
}