当前位置:主页 > 软件编程 > JAVA代码 >

java中数组的应用及方法

时间:2020-10-18 13:59:32 | 栏目:JAVA代码 | 点击:

1.数组反转

复制代码 代码如下:

import java.util.Arrays;

 public class ArrayReverse {
     public static void main(String[] args){
         int[] arr ={1,2,3,4,5,6,7,8,9};
         reverse(arr);
     }
     public static void reverse(int[] arr){
         for(int i=0;i<arr.length/2;i++){
             int temp = arr[i];
             arr[i] =arr[arr.length-1-i];
             arr[arr.length-1-i]=temp;
         }
         System.out.println(Arrays.toString(arr));
     }
 }

2.求最值
复制代码 代码如下:

class  ZuiZhi
  {
      public static void main(String[] args)
      {
          int[] a={2,92,34,54,28};
          minMethod(a);
          maxMethod(a);
      }
      public static void minMethod(int[] a)
      {
          int min=a[0];//不能初始化为0 数组中可能有负数
          for (int i=0;i<a.length;i++ )
          {
              if(a[i]<min)
                  min=a[i];
          }
          System.out.println("数组内最小的元素是:"+min);
      }
      public static void maxMethod(int[] a)
      {
          int max=a[0];//不能初始化为0 数组中可能有负数
          for (int i=0;i<a.length;i++ )
          {
              if(a[i]>max)
                  max=a[i];
          }
          System.out.println("数组内最大的元素是:"+max);
      }

  }

3.折半查找
复制代码 代码如下:

/*
  折半查找:
  3 5 7 9 10 14
  min=0 max=length-1 mid=(max+min)/2
  */
  class BinarySearch
  {
      public static void main(String[] args)
      {
          int[] a={3,5,7,9,10,14};
          int index=binarySearch_1(a,7);
          System.out.println(index);
          index=binarySearch_2(a,14);
          System.out.println(index);   
      }
      public static int binarySearch_1(int[] a,int key)
      {
          int min=0,mid,max=a.length-1;
          mid=(min+max)/2;
          while (key!=a[mid])
          {
              if(a[mid]>key)
              {
                  max=mid-1;
              }
              else  if (a[mid]<key)
              {
                  min=mid+1;
              }
              if (max<min)
                  return -1;
              mid=(min+max)/2;

          }
          return mid;
      }
      public static int binarySearch_2(int[] a,int key)
      {
          int min=0,max=a.length-1,mid;
          while (min<=max)
          {
              mid =(max+min)>>1;
              if(a[mid]>key)
              {
                  max=mid-1;
              }
              else  if (a[mid]<key)
              {
                  min=mid+1;
              }
              else
                  return mid;
          }
          return -1;
      }

  }

您可能感兴趣的文章:

相关文章