有一个整数数组,其中存放着序列1,3,5,7,9,11,13,15,17,19。请将该序列倒序存放并输出。
package wu;
public class Dx {
public static void main(String[] args) {
int [] a={1,3,5,7,9,11,13,15,17,19};
int [] b=new int[a.length];
for(int i=a.length-1;i>=0;i--)
{
b[i]=a[i];
System.out.print(b[i]+" ");
}
}
}
实现二维数组整体转置。
package wu;
public class Zzhi {
public static void main(String[] args) {
int [][] a={{1,2,3},{4,5,6},{7,8,9}};
System.out.println("原数组为:");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
for (int i=0;i<a.length;i++)
{
for (int j=0;j<=i;j++)
{
int b=a[i][j];
a[i][j]=a[j][i];
a[j][i]=b;
}
}
System.out.println("转置后为:");
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
使用二分查找法在数组中查找关键字key。
package wu;
import java.util.Scanner;
public class Cz {
static int cz(int [] a,int key) {
int left=0;
int right=a.length-1;
while(left<=right) {
int mid=(left+right)/2;
if(key==a[mid]) {
return mid;
}
else if(key<a[mid]) {
right=mid-1;
}
else {
left=mid+1;
}
}
return -1;
}
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int [] a =new int[]{12,25,45,78,95,154};
System.out.println("请输入要查找的key:");
int key=sc.nextInt();
System.out.println("提示:查找key,查到输出下标位置,若没查到返回-1");
System.out.print(cz(a,key));
}
}
}