JAvaにおける配列の応用と方法

3420 ワード

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             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          {
              if(a[i]                  min=a[i];
          }
          System.out.println(" :"+min);
      }
      public static void maxMethod(int[] a)
      {
          int max=a[0];// 0
          for (int i=0;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]              {
                  min=mid+1;
              }
              if (max                  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]              {
                  min=mid+1;
              }
              else
                  return mid;
          }
          return -1;
      }

  }