ECE 291
Computer Engineering II
Lockwood, Fall 1997

 Machine Problem 3: Visual Sorting

 
Assigned:
October 7, 1997
Due Date:
October 24, 1997
Purpose:
Text-mode video, Mouse control, Recursive algorithms.
Points:
50
 

Introduction

In this MP we will investigate two sorting algorithms: The bubble sort and the recursive quick sort. We will then visualize the operation of these sorting algorithms by creating a graphical display which animates the sort as it progresses. Finally, a mouse-driven interface will be provided a friendly interface to a human user.

Imagine looking up a telephone number in an unsorted telephone book. Without having the data sorted, it would be necessary to scan though all of the names in the book just to find an individual listing. Searches and queries for data can be performed far more quickly when the data set we are searching through is in a known order.

Now imaging having the task of sorting all the names in the telephone book. Each step of the process involves comparing a pair of names and determining which name should be listed before the other. In algorithms like the bubble sort, the running time of the sort increases with the square of the number of items being sorted. In algorithms like the quicksort, the time is proportional to n * log(n).

Sorting Algorithms: Bubble Sort

Possibly the simplest sorting algorithm is the Bubble Sort.  Bubble sort works by iterating through the array of numbers (n-1) times.  Each iteration results in the largest element being placed in its correct location in the array.  Every pass through the array, a comparison is made between every element and the element next to it.  If the first element is larger than the second element, their positions are swapped.  The algorithm then moves on to the next pair of elements.  Below is the pseudo code for the Bubble Sort algorithm.

Pseudo Code: given an array from 0 to (n-1) elements.

    for i = (n-1) to 0{
        for j =  to i{
            if (Values[j] < Values[j+1])
                swap Values[j], Values[j+1]
        }
    }

A sample run through an array of integers:

In this example the sort is complete after only 3 iterations, however the Bubble sort continues to iterate through the array (n-1) times.  A more efficient sort could detect if the data is already in sorted order, and terminate the outer loop of the algorithm if that is the case. (You are not required to enhance the basic algorithm for this MP)

Because of the nested loops in the algorithm above, Bubble sort has O(n^2) running time. For small data sets (n < 10) this is not a problem.  However, the problem of sorting large arrays of integers quickly becomes intractable when using Bubble sort.  A more efficient sorting algorithm is needed.

Sorting Algorithms: Quick Sort

We know look at a recursive sorting technique called Quick Sort.  The basic algorithm for an array of integers is as follows:
  1. Partitioning Step:  Take the first element of the unsorted array of values and determine its final location in the sorted array.  This occurs when all values to the left of the element in the array are less than the element, and all values to the right of the element in the array are greater than the element.  We now have one element in its proper location and two unsorted sub arrays.
  2. Recursive Step: Perform step 1 on each unsorted array.
Each time step 1 is performed on a sub array, another element is placed in its final location of the sorted array, and two unsorted sub arrays are created.  When a sub array consists of one element, it must be sorted, therefore that element is in its final location.

The basic algorithm seems simple enough, but how do we determine the final position the first element of each sub array?  As an example, consider the following set of values (the element in bold is the partitioning element or pivot element — it will be placed in its final position in the sorted array):

Once this partitioning method has been applied on the above array, there are two unsorted sub arrays.  The sub array with values less than 37 contains 12, 2, 6, 4, 10, and 8.  The sub array with values greater than 37 contains 89, 68, and 45.  The sort continues with both sub arrays being partitioned in the same manner as the original array.  To sort the sub arrays, we simply make a recursive call to QuickSort, sorting the sub arrays.

Without going into too much detail, Quick Sort represents a sort with a best case running time of O(n lg(n)).  Using even a small dataset, such as this MP uses, this represents a large savings over Bubble Sort.  Try running MP3 and see for yourself.  The worst case running time of Quick Sort is still O(n^2) however.  Can you determine the conditions under which this exponential running time will result?

Problem Description

A Screen Shot of mp3
In this machine problem we will be using text-mode video graphics to illustrate these sorting algorithms.  The data we will be using will consist of an array of bytes representing integers between 1 and n.  Since the text screen is only 80 columns wide, and since we want to leave room for a control panel, we will make our integers range in length from between 1 and 46 or so.  The actual value will depend on how you decide to implement your user interface.  The values we will be sorting will be stored in the byte array Values. The maximum length of the bars you will sort will be specified by Barwidth and the number of bars you will sort will be specified by Numvals.  Numvals can range from 1 to 46. These are all byte-quantities.  You will populate the array with a random-number generator. As the sorting routines progress, they will keep the running total number of comparisons in the variable Compares. The variable Stepping will determine whether or not the program steps interactively through a sort, or just runs straight through.  The delay during the sorting animation is determined by Sortdelay.

You are encouraged to exercise artistic freedom when implementing the user interface, keeping in mind that your interface must have all the necessary elements: A display of up to 46 bars going down the side of the screen, a counter for the number of comparisons, 5 buttons to perform the various actions of the MP, and a speed control.  You should display a scale along the left hand side of the screen (as shown in the sample) and you should leave enough room to display "pointers" which indicate what two elements are currently being compared.  In short, the best way to discover the requirements of your MP is to play with the sample executable.  Keep in mind that regardless of where you decide to draw your buttons and screen elements, the library routines will always draw the elements in the same place (e.g., the bars will always start drawing in row 3, column 4 of the screen) so problems may arise if you combine your code with the library routines.
 

80x50 Text Mode Programming

Programming in 80x50 text mode is a direct extension of the programming for 80x25 text mode that you learned in class.  You simply have 50 rows instead of only 25.  The Video memory still starts at offset B800.  You do not need to do any page flipping; simply write to memory as if you were using 80x25 text mode with 25 more available rows. Getting the video card into 80x50 text mode requires a slight trick with the video hardware. This code is given to you in the MP3.ASM program framework.

The Procedures

You will implement the following procedures:

DrawTextScreen

DrawAllBars

DrawBar

Comparison

Delay

Random

Quicksort

BubbleSort

DistributeValues

MouseControl

Main

Scoring

Preliminary Procedure

Errors and Eratica

Final Steps

  1. Demonstrate MP3.EXE to a TA or to the instructor.  You will then be asked to recompile and demonstrate MP3 with different values for Numvals and Barwidth.  Your program must work for different values of these variables.  Once approved, you are ready to turn in your program
  2. Be prepared to answer questions about any aspect of the operation of your program.  The TA's will not accept an MP if you cannot fully explain the operation of your code.
  3. Copy you programs to the handin floppy: A:\HANDIN YourWindowsLogin
  4. Print MP3.ASM. Use small fonts to save paper.

MP3.ASM (Program framework)

        PAGE 75, 132
        TITLE   ECE291:MP3:MultiSORT:Fall97    Your Name    Hand-in Date

COMMENT * Sorting Algorithms
          ECE291: Machine Problem 3
          Fall 1997 / Lockwood
          Guest MP Author: Daniel Restelli
          University of Illinois,
          Dept. of Electrical & Computer Engineering
          Ver 1.0  *

; =================== External Library Procedures =======================
        ; LIB291 Routines
        EXTRN  BINASC:near
        EXTRN  RSAVE:near
        EXTRN  RREST:near
        EXTRN  KBDIN:near

        ; LIBMP3 routines -- Comment out and replace with your own code!
        EXTRN  Delay:near
        EXTRN  DrawTextScreen:near
        EXTRN  DrawAllBars:near
        EXTRN  DrawBar:near
        EXTRN  QuickSort:near
        EXTRN  BubbleSort:near
        EXTRN  SwapBars:near
        EXTRN  Comparison:near
        EXTRN  MainRun:near
        EXTRN  MouseControl:near

        EXTRN  MP3Xit:near

;============================== Constants ===============================
TextVidSeg     EQU  0b800h
BubbleRun      EQU  0
BubbleStep     EQU  1
QuickRun       EQU  2
QuickStep      EQU  3
Distribute     EQU  4
Slower         EQU  5
Faster         EQU  6
QuitProg       EQU  7
ESCKEY         EQU  27

; ============================ Stack Segment ============================
stkseg    segment stack
          db   64 dup ('STACK   ')
stkseg    ends

; ============================ Program Data =============================
CSEG      segment public 'CODE'
          assume  cs:CSEG, ds:CSEG, ss:stkseg, es:nothing

; ============================= Variables ===============================
NumVals        db  46
BarWidth       db  42
RandVal        dw   3
Pbuff          db   7 dup (5)
Values         db   46 dup (6)
Stepping       db   0
Compares       dw   0
sortdelay      db   2

PUBLIC    NumVals, Barwidth, Randval, Pbuff
PUBLIC    Values, Stepping, Compares, Sortdelay

; ============================= Procedures ==============================

; Your Subroutines (defined in handout)

; ---- Main Procedure ----

MAIN Proc FAR

; Initialise DS register
          MOV  AX, CSEG
          MOV  DS, AX

; Put display into 80x50 text mode
          MOV  AX, 1202h                ; Sets to 400 line scan mode
          MOV  BL, 30h
          int  10h
          MOV  AX, 3                    ; Sets to 8x8 font
          INT  10h
          MOV  AX, 1112h                ; Enter text mode
          MOV  BL, 0
          INT  10h

; Initialize the mouse hardware, Function 0000h
          MOV  AX, 0000h
          INT  33h
; Display the mouse cursor, Function 0001h
          MOV  AX, 0001h
          INT  33h

          ; ===== Comment out and put your main code here =====
          CALL MainRun

; Put display into 80x50 text mode (to reset the screen)
EndIt:    MOV  AX, 1202h
          MOV  BL, 30h
          int  10h
          MOV  AX, 3
          INT  10h
          MOV  AX, 1112h
          MOV  BL, 0
          INT  10h

          CALL MP3Xit
MAIN ENDP

; ===================== End of Proceures & Data ==========================

CSEG    ends
        end    main