PF Assignment 3
PF Assignment 3
Write the following method that returns true if the list is already sorted in increasing order.
Write a test program that prompts the user to enter a list and displays whether the list is sorted or
not. If the list is not in sorted order then sort the list and display.
ANSWER:
import java.util.Scanner;
list[i]=input.nextInt();
int temp;
if (isSorted(list))
else
if (list[i]>list[j]){
temp=list[i];
list[i]=list[j];
list[j]=temp;}
}}
System.out.println(list[i]) ;
boolean issorted=true;
if (list[i]>list[i+1])
issorted=false;
break;
return issorted;
Output:
QUESTION 4
Write the following method that tests whether the array has four consecutive numbers with the
same value. public static boolean isConsecutiveFour(int[] values) Write a test program that prompts
the user to enter a series of integers and dis plays if the series contains four consecutive numbers
with the same value. Your program should first prompt the user to enter the input size—i.e., the
number of values in the series.
ANSWER:
import java.util.Scanner;
array[i] = scanner.nextInt();
if (isConsecutiveFour(array)) {
System.out.println("The array contains four consecutive numbers with the same value.");
} else {
System.out.println("The array does not contain four consecutive numbers with the same
value.");
return true;
}
return false;
QUESTION 5:
Write the following method that merges two sorted lists into a new sorted list. Implement the
method in a way that takes at most list1.length + list2. length comparisons. Write a test program that
prompts the user to enter two sorted lists and displays the merged list. Here is a sample run. Note
that the first number in the input indicates the number of the elements in the list. This number is not
part of the list.
ANSWER:
import java.util.Scanner;
list1[i] = scanner.nextInt();
list2[i] = scanner.nextInt();
mergedList[i]=list1[i];}
mergedList[list1.length + i]=list2[i];}
int temp;
if (mergedList[i]>mergedList[j]){
temp=mergedList[i];
mergedList[i]=mergedList[j];
mergedList[j]=temp;}
}
return mergedList;
OUTPUT: