Array Interview Programs
Array Interview Programs
package com.howtodoinjava.interview;
import java.util.HashSet;
import java.util.Set;
Output:
1. public class SecondLargestInArrayExample{
2. public static int getSecondLargest(int[] a, int total){
3. int temp;
4. for (int i = 0; i < total; i++)
5. {
6. for (int j = i + 1; j < total; j++)
7. {
8. if (a[i] > a[j])
9. {
10. temp = a[i];
11. a[i] = a[j];
12. a[j] = temp;
13. }
14. }
15. }
16. return a[total-2];
17. }
18. public static void main(String args[]){
19. int a[]={1,2,5,6,3,2};
20. int b[]={44,66,99,77,33,22,55};
21. System.out.println("Second Largest: "+getSecondLargest(a,6));
22. System.out.println("Second Largest: "+getSecondLargest(b,7));
23. }}
Output:
Second Largest: 5
Second Largest: 77
import java.util.*;
public class Exercise24 {
public static void main(String[] args) {
int total_num;
int[] numbers = new int[]{1,2,3,4,6,7};
total_num = 7;
int expected_num_sum = total_num * ((total_num + 1) / 2);
int num_sum = 0;
for (int i: numbers) {
num_sum += i;
}
System.out.print( expected_num_sum - num_sum);
System.out.print("\n");
}
}
}
}
1. import java.util.Scanner;
2. public class Count_Occurrence
3. {
4. public static void main(String[] args)
5. {
6. int n, x, count = 0, i = 0;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter no. of elements you want in array:");
9. n = s.nextInt();
10. int a[] = new int[n];
11. System.out.println("Enter all the elements:");
12. for(i = 0; i < n; i++)
13. {
14. a[i] = s.nextInt();
15. }
16. System.out.print("Enter the element of which you want to count
number of occurrences:");
17. x = s.nextInt();
18. for(i = 0; i < n; i++)
19. {
20. if(a[i] == x)
21. {
22. count++;
23. }
24. }
25. System.out.println("Number of Occurrence of the Element:"+count);
26. }
27. }
Output:
$ javac Count_Occurrence.java
$ java Count_Occurrence
Enter no. of elements you want in array:5
Enter all the elements:
2
3
3
4
3
Enter the element of which you want to count number of occurrences:3
Number of Occurrence of the Element:3
import java.io.*;
class GFG
{
static int search(int ar[],
int size)
{
int a = 0, b = size - 1;
int mid = 0;
while ((b - a) > 1)
{
mid = (a + b) / 2;
if ((ar[a] - a) != (ar[mid] - mid))
b = mid;
else if ((ar[b] - b) != (ar[mid] - mid))
a = mid;
}
return (ar[mid] + 1);
}
// Driver Code
public static void main (String[] args)
{
int ar[] = { 1, 2, 3, 4, 5, 6, 8 };
int size = ar.length;
System.out.println("Missing number: " +
search(ar, size));
}
}
// This code is contributed
// by inder_verma.
Output:
Missing number: 7
import java.util.Arrays;
public class Exercise7 {
/*
Find Largest and Smallest Number in an Array Example
This Java Example shows how to find largest and smallest number in an
array.
*/
public class FindLargestSmallestNumber {
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};