1.Find the maximum number in the array
class Maximum{ /* findMax method that accepts an array of integers and returns the largest integer in the array or return -1 if there is no numbers in an array. */ public static int findMax(int a[]){ if(a.length<1) return -1; int max=a[0]; for(int i=1;i<a.length;i++){ if(a[i]>max){ max=a[i]; } } return max; } public static void main(String args[]){ int a[] = {45,76,12,34,67,89,11}; System.out.println("Maximum number is "+findMax(a)); } } /* Output Maximum number is 89 */
2.Find the minimum number in the array
class Minimum{ /* findMin method that accepts an array of integers and returns the least integer in the array or return -1 if there is no numbers in an array. */ public static int findMin(int a[]){ if(a.length<1) return -1; int min=a[0]; for(int i=1;i<a.length;i++){ if(min>a[i]){ min=a[i]; } } return min; } public static void main(String args[]){ int a[] = {45,76,12,34,67,89,11}; System.out.println("Minimum number is "+findMin(a)); } } /* Output Minimum number is 11 */
3.Merge two sorted arrays
import java.util.*; public class Merge { public static int[] merge(int[] arr1, int[] arr2) { int[] arr = new int[arr1.length + arr2.length]; int i = 0; int j = 0; int k = 0; int m = arr1.length; int n = arr2.length; while(i < m && j < n){ if(arr1[i] < arr2[j]) { arr[k++] = arr1[i++]; } else { arr[k++] = arr2[j++]; } } while(i < m){ arr[k++] = arr1[i++]; } while(j < n){ arr[k++] = arr2[j++]; } return arr; } public static void main(String[] args) { int[] arr1 = {1, 4, 5, 8, 17}; int[] arr2 = {2, 4, 8, 11, 13, 21, 23, 25}; int[] arr = merge(arr1,arr2); for(int i=0;i<arr.length;i++) System.out.print(arr[i]+"\t"); } } /* output 1 2 4 4 5 8 8 11 13 17 21 23 25 */
0 comments:
Post a Comment