欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中数组的应用及方法

程序员文章站 2023-12-04 16:17:29
1.数组反转复制代码 代码如下:import java.util.arrays; public class arrayreverse {  &...

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;
      }

  }