We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iter
Simply, you can do this
int[] arr = new int[]{34, 45, 21, 12, 54, 67, 15};
Arrays.sort(arr);
System.out.println(arr[1]);
int[] arr = { 4, 1, 2, 0, 6, 1, 2, 0 };
int smallest = Integer.MAX_VALUE;
int smaller = Integer.MAX_VALUE;
int i = 0;
if (arr.length > 2) {
for (i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smaller = smallest;
smallest = arr[i];
} else if (arr[i] < smaller && arr[i] > smallest) {
smaller = arr[i];
}
}
System.out.println("Smallest number is " + smallest);
System.out.println("Smaller number is " + smaller);
} else {
System.out.println("Invalid array !");
}
}
You can do it in O(n) time. Below is the python code
def second_small(A):
if len(A)<2:
print 'Invalid Array...'
return
small = A[0]
second_small = [1]
if small > A[1]:
second_small,small = A[0],A[1]
for i in range(2,len(A)):
if A[i] < second_small and A[i]!=small:
if A[i] < small:
second_small = small
small = A[i]
else:
second_small = A[i]
print small, second_small
A = [12, 13, 1, 10, 34, 1]
second_small(A)
public static int findSecondSmallest(int[] elements) {
if (elements == null || elements.length < 2) {
throw new IllegalArgumentException();
}
int smallest = elements[0];
int secondSmallest = elements[0];
for (int i = 1; i < elements.length; i++) {
if (elements[i] < smallest) {
secondSmallest = smallest;
smallest = elements[i];
}
else if (elements[i] < secondSmallest) {
secondSmallest = elements[i];
}
}
return secondSmallest;
}
class A{
public static void main (String args[]){
int array[]= {-5, -4, 0, 2, 10, 3, -3};
int min;
int second_min;
if(array[0]<array[1]){
min=array[0];
second_min=array[1];
}else{
min=array[1];
second_min=array[0];
}
for(int i=2;i<array.length;i++){
if(second_min > array[i] && min > array[i]){
second_min=min;
min=array[i];
}else if(second_min > array[i] && min < array[i]){
min=min;
second_min=array[i];
}
}
System.out.println(min);
System.out.println(second_min);
}
}
public static int getSecondSmallest(int[] arr){
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for(int i=0;i<arr.length;i++){
if(smallest > arr[i]){
secondSmallest = smallest;
smallest = arr[i];
}else if (secondSmallest > arr[i] && arr[i] != smallest){
secondSmallest = arr[i];
}
System.out.println(i+" "+smallest+" "+secondSmallest);
}
return secondSmallest;
}
Just gave it a try with some of the test cases and it worked. Please check if it is correct!