1 . Write a method, called isSorted, that takes an array of integers as input, a
ID: 3805182 • Letter: 1
Question
1. Write a method, called isSorted, that takes an array of integers as input, and returns true if the array is sorted in ascending order (e.g., [2,3,7,8,22,59]), and false otherwise.
2. Write a method, called find, that takes and array of integers a and an integer x as input, and returns true if x is in a
3. Write a method, called second Min, that takes an array of integers as input, and finds the second smallest element of the array. (Debug hint: once you finish writing your code, test it on array {10,1,2,3,4} and see if the result is correct)
In java and can you please explain how to do each one.
Explanation / Answer
Question 1
Answer:
public static boolean isSorted(int a[]){
if(a.length ==0 || a.length == 1){
return true;
}
for(int i=0; i<a.length-1; i++){
if(a[i] >= a[i+1])
return false;
}
return true;
}
Question 2
Answer:
public static boolean find(int a[], int n){
for(int i=0; i<a.length; i++){
if(a[i] == n){
return true;
}
}
return false;
}
Question 3
Answer:
public static int secondMin(int arr[]){
int firstMin = arr[0];
int secondMin = arr[0];
for(int i=0; i<arr.length; i++){
if (arr[i] < firstMin) {
secondMin = firstMin;
firstMin = arr[i];
} else if (arr[i] < secondMin && arr[i] > firstMin) {
secondMin = arr[i];
}
}
return secondMin;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.