0% found this document useful (0 votes)
21 views2 pages

Frequently Asked Interview Programs On Arrays

Uploaded by

manikuttanz0008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views2 pages

Frequently Asked Interview Programs On Arrays

Uploaded by

manikuttanz0008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Array Exercise

1. Write a program to bubble sort contents of an integer array.

int [] arr = {100,30,67,0,23,99,2};


int n = arr.length;
for (int i = 0; i < n-1; i++)
{
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

2. Write a program to find the index of a specific item in an array.

public class Array10 {


public static int getIndex(int[] arr, int t) {
if (arr == null) return -1;
int len = arr.length;
int i = 0;
while (i < len) {
if (arr[i] == t) return i;
else i=i+1;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {12,56,76,98,67,198,456,716,45,100,988,99};
System.out.println("Index position of 99 is: " +
getIndex (arr, 99));
System.out.println("Index position of 198 is: " +
getIndex (arr, 198));
}
}
3. Write a program to find duplicate values from an array.

int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2};

for (int i = 0; i < my_array.length-1; i++)


{
for (int j = i+1; j < my_array.length; j++)
{
if ((my_array[i] == my_array[j]) && (i != j))
{
System.out.println("Duplicate Element : "
"+my_array[j]);
}
}
}

4. Write a program to find common elements from 2 arrays.

String [] arr1 = {"RED", "BLUE", "GREEN", "ORANGE"};

String [] arr2 = {"WHITE", "RED", "BLACK", "BLUE", "BROWN"};

//Convert arr2 to String Representation


String arr2_String = Arrays.toString(arr2);

for (String x : arr1) {


if(arr2_String.contains(x)) {
System.out.println("Common Element Found : " + x);
}
}

5. Write a program to print ‘x’ in the output whenever 3 consecutive numbers are found in
an array.
Ex. For an array {12,1,2,3,56,78,99,100,101,8,9,111} => 2 x will get printed (xx)

int [] arr = {12,1,2,3,56,78,99,100,101,8,9,111,112,113};

for(int i = 0; i <= arr.length-3; i++) {


if (arr[i] + 1 == arr[i+1] && arr[i+1] + 1 == arr[i+2]) {
System.out.print("x");
i+=2;
}
}

You might also like