Category Archives: Homework

Chapter 8: 2 sorting projects

Classwork:
1. Create 3 data sets of 5000 integers: (USE ARRAYS and the light version of the quicksort algorithm)

    Data Set A: randomly generate the data in range from 1 to 5000.
    Data Set B: generate integers in range from 1 to 5000 (no duplicates) sorted in ascending order.
    Data Set C: generate integers in range from 1 to 5000 (no duplicates) sorted in descending order.
  1. Set up counters in your quick sort trace program and run the three sets separately.
  2. Find an approximate expression that relates the size of the data to the number of comparisons or visits or swaps to the data.
  3. Make a conclusion about the three different cases.

Sorting Project

Due date: February 26th, 2016

You are to write a program that tests each of five sorting algorithms with arrays of random integer values of four different sizes. You will need to keep count of the number of times the innermost steps of the sort algorithm are executed in order to judge the relative Big-O of each sort.

    The five algorithms are: selection sort, insertion sort, bubble sort, quicksort and merge sort.
    The array sizes to use are: 10, 100, 1000, and 5000.
    The Counter class and also a class that generates arrays of random integers are below.
    You will need to modify the sort code to include an increment to the counter where appropriate.

The main part of this project is the design and implementation of a driver program that will test the sorts on the same set of arrays.

  1. It should keep track of the count result for each sort for each array size and generate a table to summarize the results. A sample table is given below.

Screen Shot 2014-02-24 at 10.39.04 AM

  1. It should create a scatter plot for each of the sorts. The plot could be either text based or as a GUI. You can also use a program edaphneDKHxcel.

  2. Source code available for you to use but you can have your own program for this project.

public class Counter

{
    private static int count = 0;

    public static int getcount( )

    {
        return count;
    }

    public static void reset( )
    {
        count = 0;
    }

    public static void increment( )
    {
        count++;
    }
}


import java.util.Random;

public class RandomIntArray
{
    public static int[ ] generateArray( int n )
    {
    // generates an array of length n populated
    // with random integers

        int[ ] result = new int[n];
                Random random = new Random();
        for (int i = 0; i < n; i++)

            result[i] = random.nextInt(5*n);

        return result;
    }
}


Bubble Sort — fixed number of passes
This version of bubble sort makes a fixed number of passes (length of the array – 1). Each inner loop is one shorter than the previous one.

public static void bubbleSort1(int[] x) {
    int n = x.length;
    for (int pass=1; pass < n; pass++) {  // count how many times
        // This next loop becomes shorter and shorter
        for (int i=0; i < n-pass; i++) {
            if (x[i] > x[i+1]) {
                // exchange elements
                int temp = x[i];  
                x[i] = x[i+1];  
                x[i+1] = temp;
            }
        }
    }
}


Homework:
Start working on the project.

Chapter 8: Sorts Projects

Classwork:
The purpose of this assignment is to observe the different performance of the quick sort based on the data.

  1. Create 3 data sets of 50,000 integers:

Data Set A: randomly generate the data in range from 1 to 50,000.(no duplicates)
Data Set B: generate integers in range from 1 to 50,000 sorted in ascending order.
Data Set C: generate integers in range from 1 to 50,000 sorted in descending order.

  1. Set up a counter in your quick sort trace program and run the three sets separately.
    Your results will be meaningful depending where you put the counter. So be mindful of what you are trying to achieve.

  2. Find an expression that relates the size of the data to the number of comparisons or visits to the data.

  3. Make a conclusion about the three different cases.

NOTE: Use Arrays and the version of Quick sort we have used.

**** If your program crashes with “stack overflow”, change the number of elements from 50,000 to 10,000 ****

Documentation:
Besides the usual, explain where and why your counter is placed.
The conclusion about the behavior of the sort based on the data characteristic.

Sorting Project
Due date: February 15th, 2017

You are to write a program that tests each of five sorting algorithms with arrays of random integer values of four different sizes. You also need a counter for this project. And just like in the previous assignment you need to decide where the counter should be so the comparisons make sense for the all the sorts. The documentation must explain where and why the counter is placed.

The five algorithms are: selection sort, insertion sort, bubble sort, quick sort and merge sort.
The array sizes to use are: 10, 100, 1000, and 5000.
The Counter class and also a class that generates arrays of random integers are posted below.
You will need to modify the sort code to include an increment to the counter where appropriate.

The main part of this project is the design and implementation of a driver program that will test the sorts on the same set of arrays.

  1. It should keep track of the count result for each sort for each array size and generate a table to summarize the results. A sample table is shown.

  1. It should create a scatter plot for each of the sorts. The plot could be either text based or as a GUI. You have the option of entering the data in a spreadsheet and use the graphing feature to create the scatter plot.

  1. Use mathematical regressions to find an expression for each of the sorts’ data.

NOTE: Counter, RandomIntArray classes, and public static void bubbleSort1(int[] x) resources are optional. You can make substitutions.

import java.util.Scanner;
//********************************************************************
//  RecursiveSorts.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the merge sort and quick sort algorithms.
//********************************************************************

public class RecursiveSorts
{
   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using merge sort.
   //-----------------------------------------------------------------
   public static void mergeSort (int[] numbers)
   {
       
      doMergeSort(numbers, 0, numbers.length - 1);
   }

   //-----------------------------------------------------------------
   //  Recursively sorts the the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doMergeSort (int[] numbers, int start, int end)
   {
       
      if (start < end)
      {
         int middle = (start + end) / 2;
         doMergeSort (numbers, start, middle);
         doMergeSort (numbers, middle + 1, end);
         merge (numbers, start, middle, end);
      }
   }

   //-----------------------------------------------------------------
   //  Merges in sorted order the two sorted subarrays
   //  [start, middle] and [middle + 1, end].
   //-----------------------------------------------------------------
   private static void merge (int[] numbers, int start, int middle,
                     int end)
   {

      // This temporary array will be used to build the merged list.
      int[] tmp = new int[end - start + 1];

      int index1 = start;
      int index2 = middle + 1;
      int indexTmp = 0;

      // Loop until one of the sublists is exhausted, adding the smaller
      // of the first elements of each sublist to the merged list.
      while (index1 <= middle && index2 <= end)
      {
         if (numbers[index1] < numbers[index2])
         {
             tmp[indexTmp] = numbers[index1];
             index1++;
         }
         else
         {
             tmp[indexTmp] = numbers[index2];
             index2++;
         }
          indexTmp++;
      }

      // Add to the merged list the remaining elements of whichever sublist
      // is not yet exhausted.
      while (index1 <= middle)
      {
         tmp[indexTmp] = numbers[index1];
         index1++;
         indexTmp++;
      }
      while (index2 <= end)
      {
         tmp[indexTmp] = numbers[index2];
         index2++;
         indexTmp++;
      }


      // Copy the merged list from tmp into numbers.
      for (indexTmp = 0; indexTmp < tmp.length; indexTmp++)
      {
         numbers[start + indexTmp] = tmp[indexTmp]; 
      }

   }

   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using quick sort.
   //-----------------------------------------------------------------
   public static void quickSort (int[] numbers)
   {
      doQuickSort(numbers, 0, numbers.length - 1);
   }
   //-----------------------------------------------------------------
   //  Recursively sorts the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doQuickSort (int[] numbers, int start, int end)
   {
      if (start < end)
      {
         int middle = partition(numbers, start, end);
         doQuickSort(numbers, start, middle);
         doQuickSort(numbers, middle + 1, end);
      }
   }

   //-----------------------------------------------------------------
   //  Partitions the array such that each value in [start, middle]
   //  is less than or equal to each value in [middle + 1, end].
   //  The index middle is determined in the procedure and returned.
   //-----------------------------------------------------------------
   private static int partition (int[] numbers, int start, int end)
   {
      int pivot = numbers[start];
      int i = start - 1;
      int j = end + 1;

      // As the loop progresses, the indices i and j move towards each other.
      // Elements at i and j that are on the wrong side of the partition are
      // exchanged. When i and j pass each other, the loop ends and j is
      // returned as the index at which the elements are partitioned around.
      while (true)
      {
         i = i + 1;
         while (numbers[i] < pivot)
            i = i + 1;

         j = j - 1;
         while (numbers[j] > pivot)
            j = j - 1;

         if (i < j)
         {
            int tmp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = tmp;

            for (int index = 0; index < numbers.length; index++)
                System.out.print (numbers[index] + "   ");
         }
         else return j;
      }
   }
}

Bubble Sort — fixed number of passes
This version of bubble sort makes a fixed number of passes (length of the array – 1). Each inner loop is one shorter than the previous one.

public static void bubbleSort1(int[] x) {
    int n = x.length;
    for (int pass=1; pass < n; pass++) {  // count how many times
        // This next loop becomes shorter and shorter
        for (int i=0; i < n-pass; i++) {
            if (x[i] > x[i+1]) {
                // exchange elements
                int temp = x[i];  
                x[i] = x[i+1];  
                x[i+1] = temp;
            }
        }
    }
}

Optional Resources:

public class Counter

{
    private static int count = 0;

    public static int getcount( )

    {
        return count;
    }

    public static void reset( )
    {
        count = 0;
    }

    public static void increment( )
    {
        count++;
    }
}
import java.util.Random;

public class RandomIntArray
{
    public static int[ ] generateArray( int n )
    {
    // generates an array of length n populated
    // with random integers

        int[ ] result = new int[n];
                Random random = new Random();
        for (int i = 0; i < n; i++)

            result[i] = random.nextInt(5*n);

        return result;
    }
}


Homework:
Start working on the project.

Chapter 8: Tracing and enacting one of the sorts

February 20th, 2015

Homework:
Review the algorithms for non-recursive and recursive sorts we learned in class.
Pay special attention to how the code is written!
Monday you will have an assessment of the sort by participating in one of the following group activities:

Tracing and enacting one of the sorts.

Screen Shot 2015-02-20 at 1.51.52 PM

NOTE: Mrs. Elia will choose the groups.
2 groups of 10 for the enacting and 3 groups of 3 for tracing on posters.

Chapter 8: quicksort

February 5th, 2015

Classwork:
Trace the quicksort for the following data:


5    9    2    1    2    4    3    7


Use the lighter version of the Quicksort code:

//-----------------------------------------------------------------
   //  Sorts the specified array of integers using quick sort.
   //-----------------------------------------------------------------
   public static void quickSort (int[] numbers)
   {
      doQuickSort(numbers, 0, numbers.length - 1);
   }
   //-----------------------------------------------------------------
   //  Recursively sorts the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doQuickSort (int[] numbers, int start, int end)
   {
      if (start < end)
      {
         int middle = partition(numbers, start, end);
         doQuickSort(numbers, start, middle);
         doQuickSort(numbers, middle + 1, end);
      }
   }

   //-----------------------------------------------------------------
   //  Partitions the array such that each value in [start, middle]
   //  is less than or equal to each value in [middle + 1, end].
   //  The index middle is determined in the procedure and returned.
   //-----------------------------------------------------------------
   private static int partition (int[] numbers, int start, int end)
   {
      int pivot = numbers[start];
      int i = start - 1;
      int j = end + 1;

      // As the loop progresses, the indices i and j move towards each other.
      // Elements at i and j that are on the wrong side of the partition are
      // exchanged. When i and j pass each other, the loop ends and j is
      // returned as the index at which the elements are partitioned around.
      while (true)
      {
         i = i + 1;
         while (numbers[i] < pivot)
            i = i + 1;

         j = j - 1;
         while (numbers[j] > pivot)
            j = j - 1;

         if (i < j)
         {
            int tmp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = tmp;

         }
         else 
         {
           return j;
         }
      }
   }

Homework:
Self-Review questions 8.1 through 8.6 (Use your own words)
MC: 8.1 through 8.6

Chapter 8: Quicksort

Trace the quicksort for the following numbers:

5  9  2  1  2  4  3  7

Turn in the tracing before the end of the period.
Look at the quicksort from the text book and find the difference between the previous one and this one.
Use print statements to trace the swapping of the array elements and compare it to your own tracing.

//********************************************************************
//  RecursiveSorts.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the merge sort and quick sort algorithms.
//********************************************************************

public class RecursiveSorts
{
   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using merge sort.
   //-----------------------------------------------------------------
   public static void mergeSort (int[] numbers)
   {
      doMergeSort(numbers, 0, numbers.length - 1);
   }

   //-----------------------------------------------------------------
   //  Recursively sorts the the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doMergeSort (int[] numbers, int start, int end)
   {
      if (start < end)
      {
         int middle = (start + end) / 2;
         doMergeSort (numbers, start, middle);
         doMergeSort (numbers, middle + 1, end);
         merge (numbers, start, middle, end);
      }
   }

   //-----------------------------------------------------------------
   //  Merges in sorted order the two sorted subarrays
   //  [start, middle] and [middle + 1, end].
   //-----------------------------------------------------------------
   private static void merge (int[] numbers, int start, int middle,
                     int end)
   {
      // This temporary array will be used to build the merged list.
      int[] tmp = new int[end - start + 1];

      int index1 = start;
      int index2 = middle + 1;
      int indexTmp = 0;

      // Loop until one of the sublists is exhausted, adding the smaller
      // of the first elements of each sublist to the merged list.
      while (index1 <= middle && index2 <= end)
      {
         if (numbers[index1] < numbers[index2])
         {
             tmp[indexTmp] = numbers[index1];
             index1++;
         }
         else
         {
             tmp[indexTmp] = numbers[index2];
             index2++;
         }
          indexTmp++;
      }

      // Add to the merged list the remaining elements of whichever sublist
      // is not yet exhausted.
      while (index1 <= middle)
      {
         tmp[indexTmp] = numbers[index1];
         index1++;
         indexTmp++;
      }
      while (index2 <= end)
      {
         tmp[indexTmp] = numbers[index2];
         index2++;
         indexTmp++;
      }

      // Copy the merged list from tmp into numbers.
      for (indexTmp = 0; indexTmp < tmp.length; indexTmp++)
      {
         numbers[start + indexTmp] = tmp[indexTmp];
      }
   }

   //-----------------------------------------------------------------
   //  Sorts the specified array of integers using quick sort.
   //-----------------------------------------------------------------
   public static void quickSort (int[] numbers)
   {
      doQuickSort(numbers, 0, numbers.length - 1);
   }
   //-----------------------------------------------------------------
   //  Recursively sorts the portion of the given array beginning
   //  at start and ending at end.
   //-----------------------------------------------------------------
   private static void doQuickSort (int[] numbers, int start, int end)
   {
      if (start < end)
      {
         int middle = partition(numbers, start, end);
         doQuickSort(numbers, start, middle);
         doQuickSort(numbers, middle + 1, end);
      }
   }

   //-----------------------------------------------------------------
   //  Partitions the array such that each value in [start, middle]
   //  is less than or equal to each value in [middle + 1, end].
   //  The index middle is determined in the procedure and returned.
   //-----------------------------------------------------------------
   private static int partition (int[] numbers, int start, int end)
   {
      int pivot = numbers[start];
      int i = start - 1;
      int j = end + 1;

      // As the loop progresses, the indices i and j move towards each other.
      // Elements at i and j that are on the wrong side of the partition are
      // exchanged. When i and j pass each other, the loop ends and j is
      // returned as the index at which the elements are partitioned around.
      while (true)
      {
         i = i + 1;
         while (numbers[i] < pivot)
            i = i + 1;

         j = j - 1;
         while (numbers[j] > pivot)
            j = j - 1;

         if (i < j)
         {
            int tmp = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = tmp;
         }
         else return j;
      }
   }
}


Chapter 8: Stacks – Maze Solver Trace

Classwork:

Trace the maze solver


//********************************************************************
//  Represents a maze of characters. The goal is to get from the
//  top left corner to the bottom right, following a path of 1s.
//********************************************************************
public class Maze
{
   private final int TRIED = 3;
   private final int PATH = 7;
   private int stepCount = 0;
   private int[][] grid = { {1,1,1},
                            {1,0,1},
                            {0,0,1}};

	1	1	1
	1	0	1
	0	0	1

//-----------------------------------------------------------------
   //  Tries to recursively follow the maze. 
   //-----------------------------------------------------------------
   public boolean traverse (int row, int column)
   {
      boolean done = false;
      
      if (valid (row, column))
      {
         grid[row][column] = TRIED;  // this cell has been tried

         if (row == grid.length-1 && column == grid[0].length-1)
            done = true;  // the maze is solved
         else
         {
            done = traverse (row+1, column);     // down
            if (!done)
               done = traverse (row, column+1);  // right
            if (!done)
               done = traverse (row-1, column);  // up
            if (!done)
               done = traverse (row, column-1);  // left
         }

         if (done)  // this location is part of the final path
         {
            grid[row][column] = PATH;
            stepCount--;
         }
      }
      
      return done;
   }
   

 //-----------------------------------------------------------------
   //  Determines if a specific location is valid.
   //-----------------------------------------------------------------
   private boolean valid (int row, int column)
   {
      boolean result = false;
      stepCount++;
      // check if cell is in the bounds of the matrix
      if (row >= 0 && row < grid.length &&
          column >= 0 && column < grid[row].length)

         //  check if cell is not blocked and not previously tried
         if (grid[row][column] == 1)
            result = true;
      return result;
   }
   //-----------------------------------------------------------------
   //  Returns the maze as a string.
   //-----------------------------------------------------------------
   public String toString ()
   {
      String result = "\n";

      for (int row=0; row < grid.length; row++)
      {
         for (int column=0; column < grid[row].length; column++)
            result += grid[row][column] + "";
         result += "\n";
      }

      return result;
   }
}

//********************************************************************
//  MazeSearch.java       Author: Lewis/Loftus/Cocking
//  Demonstrates recursion.
//********************************************************************

public class MazeSearch
{
   //-----------------------------------------------------------------
   //  Creates a new maze, prints its original form, tries to
   //  solve it, and prints out its final form.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      Maze labyrinth = new Maze();
      
      System.out.println (labyrinth);

      if (labyrinth.traverse (0, 0))
         System.out.println ("The maze was successfully solved!");
      else
         System.out.println ("There is no possible path.");

      System.out.println (labyrinth);
   }
}

Assignment:

1. Maze 3 by 3 solver trace
Show the rows and columns visited by the program for this maze:

1 0 1
1 1 1
0 1 1

2. Maze 3 by 3 solver trace using stacks
Show the changes in the stacks as the visit to a path pushes the location information and then the values are pop when they are not part of the solution.
NOTE: If you want to use small pieces of paper to push information into the top of the stack, I have a good number of them for you to use.


Here is the trace for the 3 by 3 above:
(row,column)
( 0 , 0)
( 1 , 0)
( 2 , 0)
( 1 , 1)
( 0 , 0)
( 1 , -1)
( 0 , 1)
( 1 , 1)
( 0 , 2)
( 1 , 2)
( 2 , 2)

Chapter 8: Recursive Sorts

February 20th, 2014

Recursive Sorts – Clwk 2/20 – Quick Sort Exercises Part 2
With a partner find 7 different integers to demonstrate
1. The worst case for the quick sort. (most number of swaps)
2. The best case for the quick sort. (least number of swaps)

Post both sets and the number of swaps here.

Recursive Sorts – Clwk 2/20 – Quick Sort Exercises Part 3
1. What is the difference between the quick sort original code and the one from the text book?

Homework:
Recursive Sorts – Hwk 2/20 – Quick Sort random pivot
Write a different quick sort program:
Selection of pivot: choose the first three numbers and randomly assign one of them to be the pivot.

Implementation for the assignments:

/********************************************************************
   ********************************************************************/
   public void quickSort (int[] data, int min, int max)
   {
      int indexofpartition;

      if (max - min  > 0)
      {
         /** Create partitions */
         indexofpartition = findPartition(data, min, max);

         quickSort(data, min, indexofpartition - 1);

         quickSort(data, indexofpartition + 1, max);
      }
   }

   /********************************************************************
   ********************************************************************/
   private int findPartition (int[] data, int min, int max)
   {
      int left, right;
      int temp, partitionelement;

      partitionelement = data[min]; 
      left = min;
      right = max;

         while (left partitionelement) 
            right--;

         if (left
					

Chapter 8: Merge Sort

Merge Sort
The merge sort algorithm, another recursive sort algorithm, sorts a list by recursively dividing the list in half until each sublist has one element and then recombining these sublists in order.

General Strategy:
• Begin by dividing the list in two roughly equal parts and then recursively calling itself with each of those lists.
• Continue the recursive decomposition of the list until the base case of the recursion is reached, where the list is divided into lists of length one, which are by definition sorted.
• Then, as control passes back up the recursive calling structure, the algorithm merges into one sorted list the two sorted sublists resulting from the two recursive calls.

Example:
Let’s look at the recursive decomposition portion of the algorithm.
The merge portion of the algorithm would then recombine the list.

Merge-sort-example-300px

Merge Sort Code

wiki media

wiki media

Assignment
1. The merge sort: Trace the indices for the given data:
int[] grades = {3,2,5,2};
Is it a stable sort? Explain
Use the code to supports your answer.

Good resources:

Screen Shot 2015-02-09 at 3.01.25 PM

These are two good video with details and mathematical analysis:

Chapter 8: Recursive Binary Search

Program: Implement Binary search in java using recursive algorithm.

A binary search or half-interval search algorithm finds the position of a specified value (the input “key”) within a sorted array. In each step, the algorithm compares the input key value with the key value of the middle element of the array. If the keys match, then a matching element has been found so its index, or position, is returned. Otherwise, if the sought key is less than the middle element’s key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the input key is greater, on the sub-array to the right. If the remaining array to be searched is reduced to zero, then the key cannot be found in the array and a special “Not found” indication is returned.

Every recursion eliminates half of the remaining possibilities. This makes binary searches very efficient – even for large collections.

Binary search requires a sorted collection. Also, binary searching can only be applied to a collection that allows random access (indexing).

Worst case performance: O(log n)

Best case performance: O(1)

Recursion is used in this algorithm because with each pass a new array is created by cutting the old one in half. The binary search procedure is then called recursively, this time on the new array. Typically the array’s size is adjusted by manipulating a beginning and ending index. The algorithm exhibits a logarithmic order of growth because it essentially divides the problem domain in half with each pass.

Chapter 8: Intro to Recursion – More Basic Exercises

Classwork and homework assignments

  • 1. Write a program, sumRec_YI.java with a recursive method to calculate the sum of the first N numbers.
  • 2. Write a program, binarySearchRec_YI.java, with a recursive method to find an integer in an integer array of N elements.
  • 3. Write a program, palindromeWordTestRec_YI.java, with a recursive method to determine if a word is a palindrome. It returns a boolean.
  • 4. Write a program, palindromeSentenceTestRec_YI.java, with a recursive method to determine if a sentence is a palindrome. It returns a boolean.