The application and method of array in Java _java

Source: Internet
Author: User

1. Array inversion

Copy Code code as follows:

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. Find the best value
Copy Code code as follows:

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];//cannot be initialized to 0 in an array may have negative numbers
for (int i=0;i<a.length;i++)
{
if (a[i]<min)
Min=a[i];
}
System.out.println ("The smallest element within the array is:" +min);
}
public static void Maxmethod (int[] a)
{
int max=a[0];//cannot be initialized to 0 in an array may have negative numbers
for (int i=0;i<a.length;i++)
{
if (A[i]>max)
Max=a[i];
}
System.out.println ("The largest element in the array is:" +max);
}

}

3. Binary search
Copy Code code as follows:

/*
Binary search:
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;
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.