Thursday 25 August 2016

Chapter 7 Exercise 19, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**7.19 (Sorted?) Write the following method that returns true if the list is already sorted in increasing order. public static boolean isSorted(int[] list) Write a test program that prompts the user to enter a list and displays whether the list is sorted or not. 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.
Enter list: 8 10 1 5 16 61 9 11 1
The list is not sorted

Enter list: 10 1 1 3 4 4 5 7 9 11 21
The list is already sorted 



import java.util.Scanner;
 
 
public class ProgrammingEx7_19 {
 
 public static void main(String[] args) {
 
  System.out.print("Enter list: ");
  Scanner input = new Scanner(System.in);
  int n = input.nextInt();
  int[] list = new int[n];
 
  for (int i = 0; i < list.length; i++) {
   list[i] = input.nextInt();
  }
 
  String s = " not ";
  if (isSorted(list))
   s = " already ";
 
  System.out.print("The list is" + s + "sorted");
 
 }
 
 public static boolean isSorted(int[] list) {
 
  int n = list.length - 1;
  boolean isSorted = true;
 
  for (int i = 0; i < n; i++) {
   if (list[i] > list[i + 1]) {
    isSorted = false;
    break;
   }
  }
 
  return isSorted;
 
 }
 
}

1 comment :

  1. thank you so much. you dont know how much i needed the help

    ReplyDelete