What makes a program easy to modify

Assignment Help JAVA Programming
Reference no: EM1387817

1. What makes a program easy to modify?

2. Describe the order of magnitude of the following code section using Big(O) notation.

j = 1;

While (j < N)

{

  j = j * 2);

}

3. What are the benefits we accrue by using a Java interface construct to formally specify the logical level of ADTs?

4. Suppose we have a linked list of Strings, as defined in the textbook, named presidents. Suppose it contains three nodes, with the first node holding "Adams", the second node "Washington", and the third node "Kennedy". What would be output by the following code:

LLStringNode temp = presidents;

while (temp != null)

{

temp = temp.getLink();

}

System.out.println(temp.getInfo());

5. Suppose a collection object is defined to hold elements of class Object, and you use it to store String objects. Describe what you must do when you retrieve an object from the collection and intend to use it as a String.

6. Show what is written by the following segment of code, given that item1, item2, and item3 are int variables, and stack is an object that fits our abstract description of a stack. Assume that you can store and retrieve variables of type int on stack.

item1 = 1;

item2 = 0;

item3 = 4;

stack.push(item2);

stack.push(item1);

stack.push(item1 + item3);

item2 = stack.top();

stack.push (item3*item3);

stack.push(item2);

stack.push(3);

item1 = stack.top();

stack.pop();

System.out.println(item1 + " " + item2 + " " + item3);

while (!stack.isEmpty())

{

  item1 = stack.top();

stack.pop();

System.out.println(item1);

}

7. Explain the relationship between dynamic storage allocation and recursion.

8. Analyze the factorial method and answer the following questions:

int factorial (int n)

{

if (n > 0)

return (n * factorial (n - 1));

else

if (n == 0)

return 1;

}

a. What is the base case?

b. What is the general case?

c. What are the constraints on the argument values?

d. What does the method do?

9. What are the three interfaces we defined related to our Queue ADT?

10. Describe in general terms the approach we use to implement an unbounded queue based on an array.

11. What does it mean for a class's equals and compareTo methods to be "consistent"?

12.  Questions a-e below refer to the following figure:

a. What are the ancestors of node J?

b. What are the descendants of node T?

c. What are the descendants of node B?

d. What is the order in which the nodes are visited by a preorder traversal?

e. What is the order in which the nodes are visited by a postorder traversal?

13. If a heap is used to implement a priority queue, what is the Big O efficiency of the enqueue operation, assuming the size of the priority queue is N?

14.  What would be the order of the following list after two iterations of the "inner" part of the Insertion Sort algorithm?

13         4          16         19         2          15         12         3          23         20

15.  Suppose we are using Merge Sort to sort the following list of numbers. What would be the order of the list immediately before the execution of the merge method in the original (non-recursive) call to mergesort?

13         4          16         19         2          15         12         3          23         20

16.  Programming Sorting Algorithms: For this section, use the Sorts.java test harness (provided by instructor).

a. Describe an approach to modifying the Sorts.java program so that after calling a sorting method the program prints out the number of swaps needed by the sorting method.

b. Implement your approach.

c. Test your new program by running the selectionSort method. Your program should report 49 swaps.

d. Now, modify your program to also output the number of comparisons (compares) needed. You must include one or more statements to increment your counter within the sorting methods themselves. For each of the listed methods, make and test the changes needed, and list both the number of swaps and the number of compares needed by the Sorts program to sort an array of 50 random integers.

selectionSort     swaps:____       compares:____

bubbleSort        swaps:____       compares:____

shortBubble      swaps:____       compares:____

insertionSort     swaps:____       compares:____

 

//----------------------------------------------------------------------------
// Sorts.java
//
// Test harness used to run sorting algorithms.
//----------------------------------------------------------------------------

import java.util.*;
import java.text.DecimalFormat;

public class Sorts
{
  static final int SIZE = 50;            // size of array to be sorted
  static int[] values = new int[SIZE];   // values to be sorted

  static void initValues()
  // Initializes the values array with random integers from 0 to 99.
  {
    Random rand = new Random();
    for (int index = 0; index < SIZE; index++)
      values[index] = Math.abs(rand.nextInt()) % 100;
  }

  static public boolean isSorted()
  // Returns true if the array values are sorted and false otherwise.
  {
    boolean sorted = true;
    for (int index = 0; index < (SIZE - 1); index++)
      if (values[index] > values[index + 1])
        sorted = false;
    return sorted;
  }

  static public void swap(int index1, int index2)
  // Precondition: index1 and index2 are >= 0 and < SIZE.
  //
  // Swaps the integers at locations index1 and index2 of the values array.
  {
    int temp = values[index1];
    values[index1] = values[index2];
    values[index2] = temp;
  }

  static public void printValues()
  // Prints all the values integers.
  {
    int value;
    DecimalFormat fmt = new DecimalFormat("00");
    System.out.println("The values array is:");
    for (int index = 0; index < SIZE; index++)
    {
      value = values[index];
      if (((index + 1) % 10) == 0)
        System.out.println(fmt.format(value));
      else
        System.out.print(fmt.format(value) + " ");
    }
    System.out.println();
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Selection Sort

  static int minIndex(int startIndex, int endIndex)
  // Returns the index of the smallest value in
  // values[startIndex]..values[endIndex].
  {
    int indexOfMin = startIndex;
    for (int index = startIndex + 1; index <= endIndex; index++)
      if (values[index] < values[indexOfMin])
        indexOfMin = index;
    return indexOfMin;
  }

  static void selectionSort()
  // Sorts the values array using the selection sort algorithm.
  {
    int endIndex = SIZE - 1;
    for (int current = 0; current < endIndex; current++)
      swap(current, minIndex(current, endIndex));
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Bubble Sort

  static void bubbleUp(int startIndex, int endIndex)
  // Switches adjacent pairs that are out of order
  // between values[startIndex]..values[endIndex]
  // beginning at values[endIndex].
  {
    for (int index = endIndex; index > startIndex; index--)
      if (values[index] < values[index - 1])
        swap(index, index - 1);
  }
 
  static void bubbleSort()
  // Sorts the values array using the bubble sort algorithm.
  {
    int current = 0;
 
    while (current < (SIZE - 1))
    {
      bubbleUp(current, SIZE - 1);
      current++;
    }
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Short Bubble Sort

  static boolean bubbleUp2(int startIndex, int endIndex)
  // Switches adjacent pairs that are out of order
  // between values[startIndex]..values[endIndex]
  // beginning at values[endIndex].
  //
  // Returns false if a swap was made; otherwise, returns true.
  {
    boolean sorted = true;
    for (int index = endIndex; index > startIndex; index--)
      if (values[index] < values[index - 1])
      {
        swap(index, index - 1);
        sorted = false;
      }
    return sorted;
  }
 
  static void shortBubble()
  // Sorts the values array using the bubble sort algorithm.
  // The process stops as soon as values is sorted.
  {
    int current = 0;
    boolean sorted = false;
    while ((current < (SIZE - 1)) && !sorted)
    {
      sorted = bubbleUp2(current, SIZE - 1);
      current++;
    }
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Insertion Sort

  static void insertItem(int startIndex, int endIndex)
  // Upon completion, values[0]..values[endIndex] are sorted.
  {
    boolean finished = false;
    int current = endIndex;
    boolean moreToSearch = true;
    while (moreToSearch && !finished)
    {
      if (values[current] < values[current - 1])
      {
        swap(current, current - 1);
        current--;
        moreToSearch = (current != startIndex);
      }
      else
        finished = true;
    }
  }
 
  static void insertionSort()
  // Sorts the values array using the insertion sort algorithm.
  {
   for (int count = 1; count < SIZE; count++)
      insertItem(0, count);
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Merge Sort

  static void merge (int leftFirst, int leftLast, int rightFirst, int rightLast)
  // Preconditions: values[leftFirst]..values[leftLast] are sorted.
  //                values[rightFirst]..values[rightLast] are sorted.
  //
  // Sorts values[leftFirst]..values[rightLast] by merging the two subarrays.
  {
    int[] tempArray = new int [SIZE];
    int index = leftFirst;
    int saveFirst = leftFirst;  // to remember where to copy back
 
    while ((leftFirst <= leftLast) && (rightFirst <= rightLast))
    {
      if (values[leftFirst] < values[rightFirst])
      {
        tempArray[index] = values[leftFirst];
        leftFirst++;
      }
      else
      {
        tempArray[index] = values[rightFirst];
        rightFirst++;
      }
      index++;
    }
 
    while (leftFirst <= leftLast)
    // Copy remaining items from left half.
 
    {
      tempArray[index] = values[leftFirst];
      leftFirst++;
      index++;
    }
 
    while (rightFirst <= rightLast)
    // Copy remaining items from right half.
    {
      tempArray[index] = values[rightFirst];
      rightFirst++;
      index++;
    }
 
    for (index = saveFirst; index <= rightLast; index++)
      values[index] = tempArray[index];
  }

  static void mergeSort(int first, int last)
  // Sorts the values array using the merge sort algorithm.
  {
    if (first < last)
    {
      int middle = (first + last) / 2;
      mergeSort(first, middle);
      mergeSort(middle + 1, last);
      merge(first, middle, middle + 1, last);
    }
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Quick Sort

  static int split(int first, int last)
  {
    int splitVal = values[first];
    int saveF = first;
    boolean onCorrectSide;
 
    first++;
    do
    {
      onCorrectSide = true;
      while (onCorrectSide)             // move first toward last
        if (values[first] > splitVal)
          onCorrectSide = false;
        else
        {
          first++;
          onCorrectSide = (first <= last);
        }
 
      onCorrectSide = (first <= last);
      while (onCorrectSide)             // move last toward first
        if (values[last] <= splitVal)
          onCorrectSide = false;
        else
         {
          last--;
          onCorrectSide = (first <= last);
         }
  
      if (first < last)               
      {
        swap(first, last);
        first++;
        last--;
      }
    } while (first <= last);
 
    swap(saveF, last);
    return last;
  }

  static void quickSort(int first, int last)
  {
    if (first < last)
    {
      int splitPoint;
 
      splitPoint = split(first, last);
      // values[first]..values[splitPoint - 1] <= splitVal
      // values[splitPoint] = splitVal
      // values[splitPoint+1]..values[last] > splitVal
 
      quickSort(first, splitPoint - 1);
      quickSort(splitPoint + 1, last);
    }
  }


  /////////////////////////////////////////////////////////////////
  //
  //  Heap Sort

  static int newHole(int hole, int lastIndex, int item)
  // If either child of hole is larger than item this returns the index
  // of the larger child; otherwise it returns the index of hole.
  {
    int left = (hole * 2) + 1;
    int right = (hole * 2) + 2;
    if (left > lastIndex)
      // hole has no children
      return hole;        
    else
    if (left == lastIndex)
      // hole has left child only
      if (item < values[left])            
        // item < left child
        return left;
      else
        // item >= left child
        return hole;
    else
    // hole has two children
    if (values[left] < values[right])
      // left child < right child
      if (values[right] <= item)
        // right child <= item
        return hole;
      else
        // item < right child
        return right;
    else
    // left child >= right child
    if (values[left] <= item)
      // left child <= item
      return hole;
    else
      // item < left child
      return left;
  }

  static void reheapDown(int item, int root, int lastIndex)
  // Precondition: Current root position is "empty".
  //
  // Inserts item into the tree and ensures shape and order properties.
  {
    int hole = root;   // current index of hole
    int newhole;       // index where hole should move to

    newhole = newHole(hole, lastIndex, item);   // find next hole
    while (newhole != hole)
    {
      values[hole] = values[newhole];      // move value up
      hole = newhole;                      // move hole down
      newhole = newHole(hole, lastIndex, item);     // find next hole
    }
    values[hole] = item;           // fill in the final hole
  }

  static void heapSort()
  // Sorts the values array using the heap sort algorithm.
  {
    int index;
    // Convert the array of values into a heap.
    for (index = SIZE/2 - 1; index >= 0; index--)
      reheapDown(values[index], index, SIZE - 1);
 
    // Sort the array.
    for (index = SIZE - 1; index >=1; index--)
    {
      swap(0, index);
      reheapDown(values[0], 0, index - 1);
    }
  }

  /////////////////////////////////////////////////////////////////
  //
  //  Main

  public static void main(String[] args)
  {
    initValues();
    printValues();
    System.out.println("values is sorted: " + isSorted());
    System.out.println();
   
    // make call to sorting method here (just remove //)
    // selectionSort();
    // bubbleSort();
    // shortBubble();
    // insertionSort();
    // mergeSort(0, SIZE - 1);
    // quickSort(0, SIZE - 1);
    // heapSort();

    printValues();
    System.out.println("values is sorted: " + isSorted());
    System.out.println();
  }
}

Reference no: EM1387817

Questions Cloud

Program to compute surface area of sphere using function : Write down a program in C++ to compute surface area of sphere using a function. As sample run, write down the surface areas of spheres with radii.
Determine the phenotypic ratio of the offspring : Two plants in a cross were each heterozygous for two gene pairs whose loci are linked and twenty-five mu apart. Assuming that crossing over occurs during formation of both male and female gametes
Osha materials safety data sheets : Determine a health policy, such as OSHA's Materials Safety Data Sheets, that has changed or affected health care today. How does this event illustrate the changes to health care?
Type of p-value in designing a research study : A doctoral student is designing a research study. She is hoping that the results of the study are statistically significant. What type of p-value would she want to obtain? Select one of the following.
What makes a program easy to modify : Describe the order of magnitude of the code section using Big(O) notation and Explain the relationship between dynamic storage allocation and recursion.
Determine universal precautions : Determine what additional data do you think is necessary for healthcare professionals and students to know? Do some additional research on the subject of laboratory safety and share your findings with your classmates and determine universal precautio..
Entrepreneurial new-economy ventures : It is likely you have thought of an idea(s) for entrepreneurial new-economy ventures. If not, think of one now
Java program to read line of text which ends with period : Write down the java program which will read the line of text which ends with the period, which serves as sentinel value. Show all the letters which occur in the text.
What is the p-value of the self-serve gasoline stations : An automotive expert claims that the large number of self-serve gasoline stations has resulted in poor automobile maintenance, and that the average tire pressure is more than 4 pounds per square inch (psi) below its manufacturer's specification.

Reviews

Write a Review

JAVA Programming Questions & Answers

  Write java program which will permit user to make selection

Write the Java Program which will permit the user to make selection. You will present user with two options to perform, then you will perform action selected by user.

  Rock-paper-scissors :- java problem

Design decision marks are based on how you implemented our programs/classes.

  Create application uses two-dimensional arrays

Create an application which uses 2-dimensional arrays to keep track of 5 students' grades, with each student having 3 different classes.

  Java program to ask user to enter favorite color

Write a Java program to ask the user to enter favorite color, a favorite food, favorite animal, and first name of a friend or relative.

  Java program for line item application

This exercise explains you the process of testing and enhancing Line Item application. Open LineItemApp, Validator, Product, LineItem, and ProductDB classes that are in the c:java1.6ch06LineItem directory and review this code.

  Write java program that writes names to text file

Create an empty text file called myfile.txt. Write a Java program that writes your names to the text file created. If the file does not exist, include an exception handler for that error.

  Write down java program for furniture company

Write down a Java program for the furniture company. Ask user to select P for Pine, O for Oak or M for Mahogany. Illustrate price of table manufactured with chosen wood.

  Write java programming to show number of credits for course

Write the java programming to solve following problem. We are given a student's marks in Calculus 1, CS1, and Physics 1 (each mark being between 0 and 100) also number of credits for each course.

  Represent one book in java

Represent one book in java

  Write java program which will permit user to input data

Write the Java Program which will permit the user to input data. The data will be validated using a loop that requires the user to input the data until it is correct or in the correct range. T

  Java program use breadth-first search closest broadcast

Write the java program which will use breadth-first search (which you implement as part of your program) to determine the closest broadcast vertex for each vertex in graph.

  Write a program that shows the current time and date

Write a program that shows the current time and date

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd