In: Computer Science
write a method that returns the index of the second smallest
element in an array of integers. If the number of such elements is
greater than 1. return the second smallest index. Use the following
header:public static int index of seconds sma11eststenent tint
array
Below code has comment section explains the program flow.
Code:
import java.util.Scanner;
public class Second_Small{
public static void main(String []args)
{
int n, res;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array(Minimum
2):");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
//Get array elem#ents
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
//calling method to find 2nd smallest element in the array
res = index_second_smallest(a);
System.out.println("Second smallest element in the array: " +
a[res]);
System.out.println("Index of second smallest element in the array:
" + res);
}
public static int index_second_smallest(int[] arr)
{
int i, j, count, small, sec_small;
int index[] = new int[10];
small=arr[0];
//find the smallest element in the array
for(i=0;i
if(arr[i]
{
small=arr[i];
}
}
//find the second smallest element in the array by comparing the
smallest element
sec_small=arr[0];
for(i=0;i
if(arr[i]
sec_small=arr[i];
//index = i;
}
}
//If more than 1 sec_small elements in the array, find the second
smallest index
j=0;
count= -1;
for(i=0;i
if(arr[i]==sec_small)
{
index[j]=i;
j++;
count++;
}
}
if(count==0)
return index[0];
else
return index[1];
}
}
Output: