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