java 중수조의 응용 및 방법
3025 단어 java 배열
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;
}
}