Monday, 30 May 2022

Find max Value and min Value from Array

 

Find Max Value



import java.util.Arrays;


public class Example2 {
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 100, 50, 500, 1, 90 };
maxValueUsingMaxVal(arr);
}


public static void usingSort(int arr[]) {
Arrays.sort(arr);
System.out.println(arr[arr.length - 1]);
}


public void maxValueUsingFirstVal(int arr[]) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[0] < arr[i + 1]) {
int temp = arr[0];
arr[0] = arr[i + 1];
arr[i + 1] = temp;
}
}
System.out.println(arr[0]);
}

public static void maxValueUsingMaxVal(int arr[]) {

int maxval=Integer.MIN_VALUE;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] >maxval ) {
maxval=arr[i];
}
}
System.out.println(maxval);
}


}


Find MinValue

just change the operator value for find min Value 


System.out.println(arr[0]);


if (arr[0] > arr[i + 1]) 


if (arr[i] <maxval ) 


---------------------------------------------------\

Binary Search


public class Example3 {
public static void main(String[] args) {
int arr[] = { 10, 20, 30, 40, 50, 60, 70 };
int output = binarySearch(arr, 0, arr.length - 1, 60);
int output1 = binarySearch1(arr, 60);
System.out.println(output1);
}
public static int binarySearch(int arr[], int start, int end, int key) {
// intial condition
if (arr.length < 0) {
return -1;
}
int mid = start + (end - start) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
return binarySearch(arr, start, mid - 1, key);
} else {
return binarySearch(arr, mid + 1, end, key);
}
}
public static int binarySearch1(int arr[], int key) {
// intial condition
if (arr.length < 0) {
return -1;
}
int start = 0;
int end = arr.length - 1;
while (start < end) {
int mid = start + (end - start) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] > key) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}



No comments:

Post a Comment

06/20/024 ( TODO)

Q1 : Create array , add element ,remove element , and update the element  Q2: Show me how overloading and overriding work in inheritance wit...