Initial revision
commit
a231da731d
|
@ -0,0 +1,83 @@
|
|||
//********************************************************************
|
||||
// CD.java Author: Lewis and Loftus
|
||||
//
|
||||
// Represents a compact disc.
|
||||
//********************************************************************
|
||||
|
||||
import java.text.DecimalFormat;
|
||||
|
||||
public class CD implements Comparable, Radixable
|
||||
{
|
||||
private String title, artist;
|
||||
private double value;
|
||||
private int tracks;
|
||||
|
||||
//-----------------------------------------------------------------
|
||||
// Creates a new CD with the specified information.
|
||||
//-----------------------------------------------------------------
|
||||
public CD (String theTitle, String theArtist, double theValue, int theTracks)
|
||||
{
|
||||
title = theTitle;
|
||||
artist = theArtist;
|
||||
value = theValue;
|
||||
tracks = theTracks;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------
|
||||
// Returns a description of this CD.
|
||||
//-----------------------------------------------------------------
|
||||
public String toString()
|
||||
{
|
||||
DecimalFormat fmt=new DecimalFormat("0.00");
|
||||
String description = "$" + fmt.format(value) + " " + tracks + " " + title + " " + artist;
|
||||
return description;
|
||||
}
|
||||
|
||||
public String getTitle()
|
||||
{
|
||||
return title;
|
||||
}
|
||||
|
||||
public double getPrice()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
public String getArtist()
|
||||
{
|
||||
return artist;
|
||||
}
|
||||
|
||||
public int getTracks()
|
||||
{
|
||||
return tracks;
|
||||
}
|
||||
|
||||
public void setTracks(int tempTracks)
|
||||
{
|
||||
tracks=tempTracks;
|
||||
}
|
||||
|
||||
public void setPrice(double tempPrice)
|
||||
{
|
||||
value=tempPrice;
|
||||
}
|
||||
|
||||
public int compareTo (Object other)
|
||||
{
|
||||
//define the way that CD's are compared-- in this case, alphabetically by title
|
||||
//comparing the objects is reduced to comparing the strings that make up the title
|
||||
int result;
|
||||
result = (this.getTitle().toLowerCase().compareTo( ((CD) other).getTitle().toLowerCase() ));
|
||||
return result;
|
||||
}
|
||||
|
||||
public char getRadixChar(int index) {
|
||||
try {
|
||||
return title.charAt(index);
|
||||
}
|
||||
catch (StringIndexOutOfBoundsException e) {
|
||||
return ' ';
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
public class Data
|
||||
{
|
||||
|
||||
private double x;
|
||||
private double y;
|
||||
|
||||
public Data(double x,double y)
|
||||
{
|
||||
this.x=x;
|
||||
this.y=y;
|
||||
}
|
||||
|
||||
public double getX()
|
||||
{
|
||||
return x;
|
||||
}
|
||||
|
||||
public double getY()
|
||||
{
|
||||
return y;
|
||||
}
|
||||
|
||||
public boolean equals(Data otherData)
|
||||
{
|
||||
if (x==otherData.getX() && y==otherData.getY())
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
import java.util.*;
|
||||
import java.awt.Color;
|
||||
|
||||
public class DataVector
|
||||
{
|
||||
|
||||
private Vector myVector;
|
||||
private int size;
|
||||
private Color myColor;
|
||||
private String title;
|
||||
|
||||
public DataVector(String title,Color myColor)
|
||||
{
|
||||
this.title=title;
|
||||
myVector=new Vector();
|
||||
size=0;
|
||||
this.myColor=myColor;
|
||||
}
|
||||
|
||||
public void addPoint(double x, double y)
|
||||
{
|
||||
myVector.add(new Data(x,y));
|
||||
size++;
|
||||
}
|
||||
|
||||
public double getX(int index)
|
||||
{
|
||||
return ((Data) myVector.elementAt(index)).getX();
|
||||
}
|
||||
|
||||
public double getY(int index)
|
||||
{
|
||||
return ((Data) myVector.elementAt(index)).getY();
|
||||
}
|
||||
|
||||
public int size()
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
public String getTitle()
|
||||
{
|
||||
return title;
|
||||
}
|
||||
|
||||
public Color getColor()
|
||||
{
|
||||
Color temp=new Color(myColor.getRed(),myColor.getGreen(),myColor.getBlue());
|
||||
return temp;
|
||||
}
|
||||
|
||||
public void removePoint(double x, double y)
|
||||
{
|
||||
Data temp=new Data(x,y);
|
||||
|
||||
for (int z=0;z<size();z++)
|
||||
{
|
||||
if ( temp.equals(myVector.elementAt(z)) )
|
||||
myVector.removeElementAt(z);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
import java.awt.event.*;
|
||||
|
||||
|
||||
public class GenericWindowListener extends WindowAdapter
|
||||
{
|
||||
private static int num = 0;
|
||||
|
||||
public GenericWindowListener()
|
||||
{
|
||||
num++;
|
||||
}
|
||||
|
||||
public void windowClosing (WindowEvent event)
|
||||
{
|
||||
if (num == 1)
|
||||
System.exit(0);
|
||||
else
|
||||
{
|
||||
event.getWindow().dispose();
|
||||
num--;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
import java.awt.*;
|
||||
import java.util.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
public class Graph extends JFrame
|
||||
{
|
||||
|
||||
private DataVector[] points=new DataVector[10]; //max number of data series possible
|
||||
private int xaxis;
|
||||
private int yaxis;
|
||||
private final double XSIZE; //size of the monitor in pixels
|
||||
private final double YSIZE;
|
||||
private final int CIRCLESIZE=5; //size of the plotted points
|
||||
private int numArrays=0;
|
||||
|
||||
public Graph(int xaxis, int yaxis, String title)
|
||||
{
|
||||
this.xaxis=xaxis;
|
||||
this.yaxis=yaxis;
|
||||
XSIZE = Toolkit.getDefaultToolkit().getScreenSize().getWidth() - 20;
|
||||
YSIZE = Toolkit.getDefaultToolkit().getScreenSize().getHeight() - 40;
|
||||
setSize((int) XSIZE,(int) YSIZE);
|
||||
setTitle(title);
|
||||
addWindowListener(new GenericWindowListener());
|
||||
|
||||
//center the window
|
||||
Dimension ScreenSize=getToolkit().getScreenSize();
|
||||
int screenWidth=ScreenSize.width - 20;
|
||||
int screenHeight=ScreenSize.height - 40;
|
||||
setLocation((screenWidth + 10)/2-(int) XSIZE/2,(screenHeight + 20)/2-(int) YSIZE/2);
|
||||
getContentPane().add(new GraphPanel());
|
||||
show();
|
||||
}
|
||||
|
||||
public int getX()
|
||||
{
|
||||
return xaxis;
|
||||
}
|
||||
|
||||
public int getY()
|
||||
{
|
||||
return yaxis;
|
||||
}
|
||||
|
||||
public void setX(int newX)
|
||||
{
|
||||
xaxis = newX;
|
||||
}
|
||||
|
||||
public void setY(int newY)
|
||||
{
|
||||
yaxis = newY;
|
||||
}
|
||||
|
||||
public class GraphPanel extends JPanel
|
||||
{
|
||||
public void paint(Graphics g)
|
||||
{
|
||||
int xtemp=0;
|
||||
int ytemp=0;
|
||||
g.setColor(Color.black);
|
||||
g.fillRect(0,0,(int) XSIZE,(int) YSIZE);
|
||||
//convert from x,y values to proper screen coordinates
|
||||
for (int y=0;y<numArrays;y++)
|
||||
{
|
||||
g.setColor(points[y].getColor());
|
||||
for (int x=0;x<points[y].size();x++)
|
||||
{
|
||||
xtemp=(int) (points[y].getX(x)*XSIZE/xaxis);
|
||||
ytemp=(int) (YSIZE- points[y].getY(x)*YSIZE/yaxis);
|
||||
ytemp-=30; //want to be able to see the lowest points
|
||||
g.fillOval(xtemp,ytemp,CIRCLESIZE,CIRCLESIZE);
|
||||
}
|
||||
|
||||
g.drawString(points[y].getTitle(),xtemp-50,ytemp-20);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void addData(DataVector points)
|
||||
{
|
||||
this.points[numArrays]=points;
|
||||
numArrays++;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,131 @@
|
|||
|
||||
// ********************************************************
|
||||
// Array-based implementation of the ADT list.
|
||||
// *********************************************************
|
||||
|
||||
import java.util.Iterator;
|
||||
|
||||
public class ListArrayBased implements ListInterface
|
||||
{
|
||||
|
||||
private int maxList;
|
||||
private Object[] items; // an array of list items
|
||||
private int size; // number of items in list
|
||||
|
||||
public ListArrayBased()
|
||||
{
|
||||
maxList=2;
|
||||
size = 0;
|
||||
items = new Object[maxList];
|
||||
} // end default constructor
|
||||
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return (size == 0);
|
||||
} // end isEmpty
|
||||
|
||||
public int size()
|
||||
{
|
||||
return size;
|
||||
} // end size
|
||||
|
||||
public void removeAll()
|
||||
{
|
||||
// Creates a new array; marks old array for
|
||||
// garbage collection.
|
||||
maxList=2;
|
||||
items = new Object[maxList];
|
||||
size = 0;
|
||||
} // end removeAll
|
||||
|
||||
public void add(int index, Object item) throws ListException
|
||||
{
|
||||
if (size >= maxList)
|
||||
{
|
||||
//throw new ListException("List full.");
|
||||
arrayResize();
|
||||
} // end if
|
||||
|
||||
if (index >= 1 && index <= size+1)
|
||||
{
|
||||
// make room for new element by shifting all items at
|
||||
// positions >= index toward the end of the
|
||||
// list (no shift if index == size+1)
|
||||
for (int pos = size; pos >= index; pos--)
|
||||
{
|
||||
items[pos] = items[pos-1];
|
||||
} // end for
|
||||
// insert new item
|
||||
items[index-1] = item;
|
||||
size++;
|
||||
}
|
||||
else
|
||||
{ // index out of range
|
||||
throw new ListException("List index out of range.");
|
||||
} // end if
|
||||
|
||||
} //end add
|
||||
|
||||
public Object get(int index) throws ListException
|
||||
{
|
||||
|
||||
if (index >= 1 && index <= size)
|
||||
{
|
||||
return items[index-1];
|
||||
}
|
||||
else
|
||||
{ // index out of range
|
||||
throw new ListException("List index out of range.");
|
||||
} // end if
|
||||
|
||||
} // end get
|
||||
|
||||
public void remove(int index) throws ListException
|
||||
{
|
||||
if (index >= 1 && index <= size)
|
||||
{
|
||||
// delete item by shifting all items at
|
||||
// positions > index toward the beginning of the list
|
||||
// (no shift if index == size)
|
||||
for (int pos = index; pos < size(); pos++)
|
||||
{
|
||||
items[pos-1] = items[pos];
|
||||
} // end for
|
||||
items[size()-1]=null; //eliminate dangling references
|
||||
size--;
|
||||
}
|
||||
else
|
||||
{ // index out of range
|
||||
throw new ListException("List index out of range.");
|
||||
} // end if
|
||||
} //end remove
|
||||
|
||||
private void arrayResize()
|
||||
{
|
||||
maxList*=2;
|
||||
Object[] temp=new Object[maxList];
|
||||
|
||||
for (int x=0;x<size;x++)
|
||||
{
|
||||
temp[x]=items[x];
|
||||
}
|
||||
|
||||
items=temp;
|
||||
}
|
||||
|
||||
public Iterator iterator()
|
||||
{
|
||||
return new ListIterator(this);
|
||||
}
|
||||
|
||||
public Object[] toArray()
|
||||
{
|
||||
Object[] tempArray=new Object[size()];
|
||||
for (int x=0;x<size();x++)
|
||||
{
|
||||
tempArray[x]=get(x+1);
|
||||
}
|
||||
return tempArray;
|
||||
}
|
||||
|
||||
} // end ListArrayBased
|
|
@ -0,0 +1,9 @@
|
|||
|
||||
public class ListException extends RuntimeException
|
||||
{
|
||||
public ListException(String s)
|
||||
{
|
||||
super(s);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,77 @@
|
|||
|
||||
import java.util.Iterator;
|
||||
|
||||
/**
|
||||
* <b><code>ListInterface</code></b> provides the user interface for the general list.
|
||||
*
|
||||
* @author
|
||||
* <a href="mailto:mboshart@tntech.edu">Mark Boshart</a>
|
||||
* @version 1.0
|
||||
*/
|
||||
public interface ListInterface
|
||||
{
|
||||
/**
|
||||
* Determines whether a list is empty. <br>
|
||||
* Precondition: None. <br>
|
||||
* Postcondition: Returns true if the list is empty, otherwise returns false. <br>
|
||||
* Throws: None.
|
||||
*/
|
||||
public boolean isEmpty();
|
||||
|
||||
/**
|
||||
* Determines the length of a list. <br>
|
||||
* Precondition: None. <br>
|
||||
* Postcondition: Returns the number of items that are currently in the list. <br>
|
||||
* Throws: None.
|
||||
*/
|
||||
public int size();
|
||||
|
||||
/**
|
||||
* Adds an item to the list at position index. <br>
|
||||
* Precondition: index indicates the position at which the item should be inserted in the list. <br>
|
||||
* Postcondition: If insertion is successful, item is at position index in the list, and other items are renumbered accordingly. <br>
|
||||
* Throws: ListException if index < 1 or index > size()+1. <br>
|
||||
* Throws: ListException if item cannot be placed on the list.
|
||||
*
|
||||
* @param index <code>int</code> position to insert the object.
|
||||
* @param item <code>Object</code> object to be inserted.
|
||||
*/
|
||||
public void add(int index, Object item) throws ListException;
|
||||
|
||||
/**
|
||||
* Retrieves a list item by position. <br>
|
||||
* Precondition: index is the number of the item to be retrieved. <br>
|
||||
* Postcondition: If 1 <= index <= size(), the item at position index in the list is returned. <br>
|
||||
* Throws: ListException if index < 1 or index > size(). <br>
|
||||
*
|
||||
* @param index <code>int</code> position to retrieve the object.
|
||||
*/
|
||||
public Object get(int index) throws ListException;
|
||||
|
||||
/**
|
||||
* Deletes an item from the list at a given position. <br>
|
||||
* Precondition: index indicates where the deletion should occur. <br>
|
||||
* Postcondition: If 1 <= index <= size(), the item at position index in the list is deleted, and other items are renumbered accordingly. <br>
|
||||
* Throws: ListException if index < 1 or index > size(). <br>
|
||||
*
|
||||
* @param index <code>int</code> position to remove the object.
|
||||
*/
|
||||
public void remove(int index) throws ListException;
|
||||
|
||||
/**
|
||||
* Deletes all the items from the list. <br>
|
||||
* Precondition: None. <br>
|
||||
* Postcondition: The list is empty. <br>
|
||||
* Throws: None.
|
||||
*/
|
||||
public void removeAll();
|
||||
|
||||
/**
|
||||
* Returns an Iterator for the list. <br>
|
||||
* Precondition: None. <br>
|
||||
* Postcondition: An Iterator is returned. <br>
|
||||
* Throws: None.
|
||||
*/
|
||||
public Iterator iterator();
|
||||
|
||||
} // end ListInterface
|
|
@ -0,0 +1,54 @@
|
|||
|
||||
import java.util.Iterator;
|
||||
|
||||
class ListIterator implements Iterator
|
||||
{
|
||||
private int index;
|
||||
private int check;
|
||||
private ListInterface list;
|
||||
|
||||
public ListIterator(ListInterface list)
|
||||
{
|
||||
index=1;
|
||||
check=list.size();
|
||||
this.list=list;
|
||||
}
|
||||
|
||||
private void check()
|
||||
{
|
||||
if (check!=list.size())
|
||||
{
|
||||
//reset iteration to the start of the list
|
||||
index=1;
|
||||
check=list.size();
|
||||
throw new ListException("Change made to collection during iteration.");
|
||||
//check can miss alterations to the list if add/remove combinations are used
|
||||
}
|
||||
}
|
||||
|
||||
public void remove()
|
||||
{
|
||||
//to be implemented
|
||||
}
|
||||
|
||||
public boolean hasNext()
|
||||
{
|
||||
check();
|
||||
return (index<=check);
|
||||
}
|
||||
|
||||
public Object next()
|
||||
{
|
||||
check();
|
||||
|
||||
if (hasNext())
|
||||
{
|
||||
index++;
|
||||
return list.get(index-1);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ListException("End of list.");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
public class Node {
|
||||
private Node next;
|
||||
private Object data;
|
||||
public Node(Object data) {
|
||||
this.data = data;
|
||||
next = null;
|
||||
}
|
||||
|
||||
public Node(Object data, Node next) {
|
||||
this.data = data;
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
public Object getItem() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setItem(Object data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public Node getNext() {
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setNext(Node next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
|
||||
public class QueueException extends RuntimeException
|
||||
{
|
||||
public QueueException(String s)
|
||||
{
|
||||
super(s);
|
||||
} // end constructor
|
||||
} // end QueueException
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
|
||||
public interface QueueInterface
|
||||
{
|
||||
/**
|
||||
* Determines whether a queue is empty.
|
||||
* Precondition: None.
|
||||
* Postcondition: Returns true if the queue is empty;
|
||||
* otherwise returns false.
|
||||
*/
|
||||
public boolean isEmpty();
|
||||
|
||||
/**
|
||||
* Adds an item at the back of a queue.
|
||||
* Precondition: item is the item to be inserted.
|
||||
* Postcondition: If the operation was successful, newItem
|
||||
* is at the back of the queue. Some implementations
|
||||
* may throw QueueException if item cannot be added to the queue.
|
||||
*/
|
||||
public void enqueue(Object item) throws QueueException;
|
||||
|
||||
/**
|
||||
* Retrieves and removes the front of a queue.
|
||||
* Precondition: None.
|
||||
* Postcondition: If the queue is not empty, the item
|
||||
* that was added to the queue earliest is returned and
|
||||
* the item is removed. If the queue is empty, the
|
||||
* operation is impossible and QueueException is thrown.
|
||||
*/
|
||||
public Object dequeue() throws QueueException;
|
||||
|
||||
/**
|
||||
* Removes all items of a queue.
|
||||
* Precondition: None.
|
||||
* Postcondition: The queue is empty.
|
||||
*/
|
||||
public void dequeueAll();
|
||||
|
||||
/**
|
||||
* Retrieves the item at the front of a queue.
|
||||
* Precondition: None.
|
||||
* Postcondition: If the queue is not empty, the item
|
||||
* that was added to the queue earliest is returned.
|
||||
* If the queue is empty, the operation is impossible
|
||||
* and QueueException is thrown.
|
||||
*/
|
||||
public Object peek() throws QueueException;
|
||||
|
||||
/**
|
||||
* Determines the length of a queue.
|
||||
* Precondition: None.
|
||||
* Postcondition: Returns the number of items that are
|
||||
* currently in the queue.
|
||||
* Throws: None.
|
||||
*/
|
||||
public int size();
|
||||
|
||||
|
||||
} // end QueueInterface
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
|
||||
public class QueueReferenceBased implements QueueInterface
|
||||
{
|
||||
// circular references
|
||||
private Node tail;
|
||||
private int size;
|
||||
|
||||
public QueueReferenceBased()
|
||||
{
|
||||
tail = null;
|
||||
size=0;
|
||||
} // end default constructor
|
||||
|
||||
// queue operations:
|
||||
public boolean isEmpty()
|
||||
{
|
||||
return tail == null;
|
||||
} // end isEmpty
|
||||
|
||||
public int size()
|
||||
{
|
||||
return size;
|
||||
}
|
||||
|
||||
public void dequeueAll()
|
||||
{
|
||||
if (tail!=null)
|
||||
tail.setNext(null);
|
||||
|
||||
tail = null;
|
||||
size=0;
|
||||
} // end dequeueAll
|
||||
|
||||
public void enqueue(Object item)
|
||||
{
|
||||
Node myNode = new Node(item);
|
||||
|
||||
// insert the new node
|
||||
if (isEmpty())
|
||||
{
|
||||
// insertion into empty queue
|
||||
myNode.setNext(myNode);
|
||||
}
|
||||
else
|
||||
{
|
||||
// insertion into nonempty queue
|
||||
myNode.setNext(tail.getNext());
|
||||
tail.setNext(myNode);
|
||||
} // end if
|
||||
|
||||
tail = myNode; // new node is at back
|
||||
size++;
|
||||
} // end enqueue
|
||||
|
||||
public Object dequeue() throws QueueException
|
||||
{
|
||||
if (!isEmpty())
|
||||
{
|
||||
// queue is not empty; remove front
|
||||
Node head = tail.getNext();
|
||||
if (head == tail)
|
||||
{ // special case?
|
||||
tail.setNext(null);
|
||||
tail = null; // yes, one node in queue
|
||||
}
|
||||
else
|
||||
{
|
||||
tail.setNext(head.getNext());
|
||||
} // end if
|
||||
size--;
|
||||
return head.getItem();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new QueueException("Queue empty");
|
||||
} // end if
|
||||
} // end dequeue
|
||||
|
||||
public Object peek() throws QueueException
|
||||
{
|
||||
if (!isEmpty())
|
||||
{
|
||||
// queue is not empty; retrieve front
|
||||
Node head = tail.getNext();
|
||||
return head.getItem();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new QueueException("Queue empty");
|
||||
} // end if
|
||||
} // end peek
|
||||
|
||||
public String toString() {
|
||||
Node temp = tail.getNext();
|
||||
String result = "";
|
||||
for (int i = 0; i < size; i++) {
|
||||
result += temp.getItem() + "\n";
|
||||
temp = temp.getNext();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // end QueueCircular
|
|
@ -0,0 +1,12 @@
|
|||
/**
|
||||
* An interface for making objects easy to sort Radixably. <BR>
|
||||
* @author <A HREF="mailto:arc4472@tntech.edu">Andrew Coleman</A>
|
||||
*/
|
||||
public interface Radixable {
|
||||
/**
|
||||
* The only method needed to sort objects Radixably. <BR>
|
||||
* Preconditions: An index in the name that is being used to sort.
|
||||
* Postconditions: Returns a char at the index, or a space if the index is invalid.
|
||||
*/
|
||||
public char getRadixChar(int index);
|
||||
}
|
|
@ -0,0 +1,401 @@
|
|||
//import trees.*;
|
||||
//import queues.*;
|
||||
|
||||
public class SortRoutines
|
||||
{
|
||||
|
||||
|
||||
// Finds the largest item in an array.
|
||||
// Precondition: theArray is an array of size items;
|
||||
// size >= 1.
|
||||
// Postcondition: Returns the index of the largest
|
||||
// item in the array.
|
||||
private static int indexOfLargest(Comparable[] theArray, int size)
|
||||
{
|
||||
int indexSoFar = 0; // index of largest item found so far
|
||||
// Invariant: theArray[indexSoFar]>=theArray[0..currIndex-1]
|
||||
for (int currIndex = 1; currIndex < size; ++currIndex)
|
||||
{
|
||||
if (theArray[currIndex].compareTo(theArray[indexSoFar])>0)
|
||||
{
|
||||
indexSoFar = currIndex;
|
||||
} // end if
|
||||
} // end for
|
||||
|
||||
return indexSoFar; // index of largest item
|
||||
} // end indexOfLargest
|
||||
|
||||
// Sorts the items in an array into ascending order.
|
||||
// Precondition: theArray is an array of n items.
|
||||
// Postcondition: theArray is sorted into
|
||||
// ascending order.
|
||||
// Calls: indexOfLargest.
|
||||
public static void selectionSort(Comparable[] theArray, int n)
|
||||
{
|
||||
// last = index of the last item in the subarray of
|
||||
// items yet to be sorted
|
||||
// largest = index of the largest item found
|
||||
|
||||
Comparable temp;
|
||||
|
||||
for (int last = n-1; last >= 1; last--) //all but
|
||||
{
|
||||
// Invariant: theArray[last+1..n-1] is sorted
|
||||
// and > theArray[0..last]
|
||||
|
||||
// select largest item in theArray[0..last]
|
||||
int largest = indexOfLargest(theArray, last+1);
|
||||
|
||||
// swap largest item theArray[largest] with
|
||||
// theArray[last]
|
||||
temp = theArray[largest];
|
||||
theArray[largest] = theArray[last];
|
||||
theArray[last] = temp;
|
||||
} // end for
|
||||
|
||||
} // end selectionSort
|
||||
|
||||
// Sorts the items in an array into ascending order.
|
||||
// Precondition: theArray is an array of n items.
|
||||
// Postcondition: theArray is sorted into ascending
|
||||
// order.
|
||||
public static void insertionSort(Comparable[] theArray, int n)
|
||||
{
|
||||
// unsorted = first index of the unsorted region,
|
||||
// loc = index of insertion in the sorted region,
|
||||
// nextItem = next item in the unsorted region
|
||||
|
||||
// initially, sorted region is theArray[0],
|
||||
// unsorted region is theArray[1..n-1];
|
||||
for (int unsorted = 1; unsorted < n; ++unsorted)
|
||||
{
|
||||
// Invariant: theArray[0..unsorted-1] is sorted
|
||||
|
||||
// find the right position (loc) in
|
||||
// theArray[0..unsorted] for theArray[unsorted],
|
||||
// which is the first item in the unsorted
|
||||
// region; shift, if necessary, to make room
|
||||
Comparable nextItem = theArray[unsorted];
|
||||
int loc = unsorted;
|
||||
|
||||
while ((loc > 0) && (theArray[loc-1].compareTo(nextItem) > 0))
|
||||
{
|
||||
// shift theArray[loc-1] to the right
|
||||
theArray[loc] = theArray[loc-1];
|
||||
loc--;
|
||||
} // end while
|
||||
// insert nextItem into sorted region
|
||||
theArray[loc] = nextItem;
|
||||
} // end for
|
||||
|
||||
} // end insertionSort
|
||||
|
||||
// Sorts the items in an array into ascending order.
|
||||
// Precondition: theArray is an array of n items.
|
||||
// Postcondition: theArray is sorted into ascending
|
||||
// order.
|
||||
public static void bubbleSort(Comparable[] theArray, int n)
|
||||
{
|
||||
boolean sorted = false; // false when swaps occur
|
||||
for (int pass = 1; (pass < n) && !sorted; ++pass)
|
||||
{
|
||||
// Invariant: theArray[n+1-pass..n-1] is sorted
|
||||
// and > theArray[0..n-pass]
|
||||
sorted = true; // assume sorted
|
||||
for (int index = 0; index < n-pass; ++index)
|
||||
{
|
||||
// Invariant: theArray[0..index-1] <= theArray[index]
|
||||
int nextIndex = index + 1;
|
||||
if (theArray[index].compareTo(theArray[nextIndex]) > 0)
|
||||
{
|
||||
// exchange items
|
||||
Comparable temp = theArray[index];
|
||||
theArray[index] = theArray[nextIndex];
|
||||
theArray[nextIndex] = temp;
|
||||
sorted = false; // signal exchange
|
||||
} // end if
|
||||
} // end for
|
||||
|
||||
// Assertion: theArray[0..n-pass-1] < theArray[n-pass]
|
||||
} // end for
|
||||
|
||||
} // end bubbleSort
|
||||
|
||||
// Merges two sorted array segments theArray[first..mid] and
|
||||
// theArray[mid+1..last] into one sorted array.
|
||||
// Precondition: first <= mid <= last. The subarrays
|
||||
// theArray[first..mid] and theArray[mid+1..last] are
|
||||
// each sorted in increasing order.
|
||||
// Postcondition: theArray[first..last] is sorted.
|
||||
// Implementation note: This method merges the two
|
||||
// subarrays into a temporary array and copies the result
|
||||
// into the original array anArray.
|
||||
private static void merge(Comparable[] theArray, int first, int mid, int last)
|
||||
{
|
||||
int maxSize = theArray.length;
|
||||
// temporary array
|
||||
Comparable[] tempArray = new Comparable[maxSize];
|
||||
|
||||
// initialize the local indexes to indicate the subarrays
|
||||
int first1 = first; // beginning of first subarray
|
||||
int last1 = mid; // end of first subarray
|
||||
int first2 = mid + 1; // beginning of second subarray
|
||||
int last2 = last; // end of second subarray
|
||||
// while both subarrays are not empty, copy the
|
||||
// smaller item into the temporary array
|
||||
int index = first1; // next available location in
|
||||
// tempArray
|
||||
while ((first1 <= last1) && (first2 <= last2))
|
||||
{
|
||||
// Invariant: tempArray[first1..index-1] is in order
|
||||
if (theArray[first1].compareTo(theArray[first2])<=0) //careful here for stable sorting
|
||||
{
|
||||
tempArray[index] = theArray[first1];
|
||||
first1++;
|
||||
}
|
||||
else
|
||||
{
|
||||
tempArray[index] = theArray[first2];
|
||||
first2++;
|
||||
} // end if
|
||||
|
||||
index++;
|
||||
} // end while
|
||||
|
||||
// finish off the nonempty subarray
|
||||
|
||||
// finish off the first subarray, if necessary
|
||||
while (first1 <= last1)
|
||||
{
|
||||
// Invariant: tempArray[first1..index-1] is in order
|
||||
tempArray[index] = theArray[first1];
|
||||
first1++;
|
||||
index++;
|
||||
} // end while
|
||||
|
||||
// finish off the second subarray, if necessary
|
||||
while (first2 <= last2)
|
||||
{
|
||||
// Invariant: tempArray[first1..index-1] is in order
|
||||
tempArray[index] = theArray[first2];
|
||||
first2++;
|
||||
index++;
|
||||
} // end while
|
||||
|
||||
// copy the result back into the original array
|
||||
for (index = first; index <= last; ++index)
|
||||
{
|
||||
theArray[index] = tempArray[index];
|
||||
} // end for
|
||||
} // end merge
|
||||
|
||||
// Sorts the items in an array into ascending order.
|
||||
// Precondition: theArray[first..last] is an array.
|
||||
// Postcondition: theArray[first..last] is sorted in
|
||||
// ascending order.
|
||||
// Calls: merge.
|
||||
public static void mergeSort(Comparable[] theArray, int first, int last)
|
||||
{
|
||||
if (first < last)
|
||||
{
|
||||
// sort each half
|
||||
int mid = (first + last)/2; // index of midpoint
|
||||
// sort left half theArray[first..mid]
|
||||
mergeSort(theArray, first, mid);
|
||||
// sort right half theArray[mid+1..last]
|
||||
mergeSort(theArray, mid+1, last);
|
||||
|
||||
// merge the two halves
|
||||
merge(theArray, first, mid, last);
|
||||
} // end if
|
||||
} // end mergesort
|
||||
|
||||
// Sorts the items in an array into ascending order.
|
||||
// Precondition: theArray[first..last] is an array.
|
||||
// Postcondition: theArray[first..last] is sorted.
|
||||
// Calls: partition.
|
||||
public static void quickSort(Comparable[] theArray, int first, int last)
|
||||
{
|
||||
int pivotIndex;
|
||||
|
||||
if (first < last)
|
||||
{
|
||||
// create the partition: S1, Pivot, S2
|
||||
pivotIndex = partition(theArray, first, last);
|
||||
|
||||
// sort regions S1 and S2
|
||||
quickSort(theArray, first, pivotIndex-1);
|
||||
quickSort(theArray, pivotIndex+1, last);
|
||||
} // end if
|
||||
} // end quickSort
|
||||
|
||||
// Partitions an array for quicksort.
|
||||
// Precondition: theArray[first..last] is an array;
|
||||
// first <= last.
|
||||
// Postcondition: Returns the index of the pivot element of
|
||||
// theArray[first..last]. Upon completion of the method,
|
||||
// this will be the index value lastS1 such that
|
||||
// S1 = theArray[first..lastS1-1] < pivot
|
||||
// theArray[lastS1] == pivot
|
||||
// S2 = theArray[lastS1+1..last] >= pivot
|
||||
// Calls: choosePivot.
|
||||
private static int partition(Comparable[] theArray, int first, int last)
|
||||
{
|
||||
// tempItem is used to swap elements in the array
|
||||
Comparable tempItem;
|
||||
// place pivot in theArray[first]
|
||||
choosePivot(theArray, first, last);
|
||||
Comparable pivot = theArray[first]; // reference pivot
|
||||
|
||||
// initially, everything but pivot is in unknown
|
||||
int lastS1 = first; // index of last item in S1
|
||||
|
||||
// move one item at a time until unknown region is empty
|
||||
|
||||
for (int firstUnknown = first + 1; firstUnknown <= last; ++firstUnknown)
|
||||
{
|
||||
// Invariant: theArray[first+1..lastS1] < pivot
|
||||
// theArray[lastS1+1..firstUnknown-1] >= pivot
|
||||
|
||||
// move item from unknown to proper region
|
||||
if (theArray[firstUnknown].compareTo(pivot) < 0)
|
||||
{
|
||||
// item from unknown belongs in S1
|
||||
++lastS1;
|
||||
tempItem = theArray[firstUnknown];
|
||||
theArray[firstUnknown] = theArray[lastS1];
|
||||
theArray[lastS1] = tempItem;
|
||||
} // end if
|
||||
// else item from unknown belongs in S2
|
||||
} // end for
|
||||
|
||||
// place pivot in proper position and mark its location
|
||||
tempItem = theArray[first];
|
||||
theArray[first] = theArray[lastS1];
|
||||
theArray[lastS1] = tempItem;
|
||||
return lastS1;
|
||||
} // end partition
|
||||
|
||||
// Chooses a pivot for quicksort's partition algorithm and
|
||||
// swaps it with the first item in an array.
|
||||
// Precondition: theArray[first..last] is an array;
|
||||
// first <= last.
|
||||
// Postcondition: theArray[first] is the pivot.
|
||||
private static void choosePivot(Comparable[] theArray, int first, int last)
|
||||
{
|
||||
|
||||
// Implementation left as an exercise.
|
||||
|
||||
} // end choosePivot
|
||||
|
||||
public static void shellSort(Comparable[] theArray, int n)
|
||||
{
|
||||
int loc;
|
||||
Comparable nextItem;
|
||||
for (int h = n/2; h > 0; h = h/2)
|
||||
{
|
||||
for (int unsorted = h; unsorted < n; ++unsorted)
|
||||
{
|
||||
nextItem = theArray[unsorted];
|
||||
loc = unsorted;
|
||||
while ((loc >= h) && (theArray[loc-h].compareTo(nextItem) > 0) )
|
||||
{
|
||||
theArray[loc] = theArray[loc-h];
|
||||
loc = loc - h;
|
||||
} // end while
|
||||
theArray[loc] = nextItem;
|
||||
} // end for unsorted
|
||||
} // end for h
|
||||
|
||||
} // end shellsort
|
||||
|
||||
|
||||
/**
|
||||
* Sorts an array of Radixable elements radixably. <BR>
|
||||
* Preconditions: An array of Radixable objects, an integer of the number of keys to sort by, and an integer of the number of elements to sort. <BR>
|
||||
* Postconditions: Returns a new array of the sorted elements. <BR>
|
||||
* @author <A HREF="mailto:arc4472@tntech.edu">Andrew Coleman</A><BR>
|
||||
* @hidden All your base are belong to us.
|
||||
*/
|
||||
public static void radixSort(Radixable[] array, int index, int n) {
|
||||
/* the maximum size of the bin array */
|
||||
/* 26 letters, 10 digits, 1 extraneous character */
|
||||
final int MAX_SIZE = 26 + 10 + 1;
|
||||
/* our array for the sorting bins */
|
||||
QueueInterface[] bins = new QueueInterface[MAX_SIZE];
|
||||
/* the array to return */
|
||||
//Radixable[] result = new Radixable[n];
|
||||
/* an array to keep the size of each bin at the end of each iteration */
|
||||
int[] binsize = new int[MAX_SIZE];
|
||||
for (int i = 0; i < MAX_SIZE; i++) {binsize[i] = 0;bins[i] = new QueueReferenceBased();}
|
||||
/* Strings are indexed with an offset of +1 */
|
||||
//index--;
|
||||
/* these next two hunks of loopage are basically the same, but this way is a big time saver
|
||||
instead of dumping the original array into a queue/array, i directly sort it into the bins
|
||||
here and the elements are not taken out of the bins until i return the result array.
|
||||
I have tried using one big loop and flags, but i get null for every item when i get done sorting.
|
||||
Besides, it saves on having to do all that extra logic checks a few hundred thousand times */
|
||||
for (int iter = 0; iter < n; iter++) {
|
||||
/* this is the only line that differs between these two loops, here it comes from the array */
|
||||
Radixable data = array[iter];
|
||||
/* get an ascii value of the character */
|
||||
int bin = (int) data.getRadixChar(index);
|
||||
/* capital letters converted to lowercase */
|
||||
if (bin >= 65 && bin <= 90)
|
||||
bin += 32;
|
||||
/* lowercase letters */
|
||||
if (bin >= 97 && bin <= 122)
|
||||
bin -= 86;
|
||||
/* numbers */
|
||||
else if (bin >=48 && bin <= 57)
|
||||
bin -= 47;
|
||||
/* non alphanumeric characters */
|
||||
else
|
||||
bin = 0;
|
||||
bins[bin].enqueue(data);
|
||||
}
|
||||
|
||||
/* already sorted the first character */
|
||||
index--;
|
||||
/* loop through remaining search keys */
|
||||
for (int loop = index; loop >= 0; loop--) {
|
||||
/* save the size of each bin */
|
||||
for (int i = 0; i < MAX_SIZE; i++) {binsize[i] = bins[i].size();}
|
||||
/* loop through each bin */
|
||||
for (int iter = 0; iter < MAX_SIZE; iter++) {
|
||||
/* loop through the number of items saved in binsize
|
||||
now you don't have to dump the elements into another queue/array */
|
||||
for (int eachbinitem = 0; eachbinitem < binsize[iter]; eachbinitem++) {
|
||||
/* get data from the bins rather than the array */
|
||||
Radixable data = (Radixable) bins[iter].dequeue();
|
||||
int bin = (int) data.getRadixChar(loop);
|
||||
if (bin >= 65 && bin <= 90)
|
||||
bin += 32;
|
||||
if (bin >= 97 && bin <= 122)
|
||||
bin -= 86;
|
||||
else if (bin >=48 && bin <= 57)
|
||||
bin -= 47;
|
||||
else
|
||||
bin = 0;
|
||||
bins[bin].enqueue(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* keeps up with the total number of elements placed in the array (always < n) */
|
||||
//int count = 0;
|
||||
/* loop through each bin */
|
||||
//for (int i = 0; i < MAX_SIZE; i++)
|
||||
/* keep dumping the items inside until it's all gone */
|
||||
// while (!bins[i].isEmpty()) {
|
||||
// result[count] = (Radixable) bins[i].dequeue();
|
||||
// count++;
|
||||
// }
|
||||
/* bye bye */
|
||||
//return result;
|
||||
/* this is sorting 200,000 strings (made by a random word generator in a Tolkien wordset) in
|
||||
about 1282 milliseconds by my primitive timing methods and by comparison i made a radixsort
|
||||
earlier that dumps everything into arrays was coming in at > 1600 milliseconds.
|
||||
*/
|
||||
}
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
import java.util.Random;
|
||||
import java.awt.*;
|
||||
|
||||
public class SortTime
|
||||
{
|
||||
private static Graph myGraph;
|
||||
private static Object[] original;
|
||||
private static Object[] originalSorted;
|
||||
private Object[] sorted;
|
||||
private static int MAX;
|
||||
|
||||
public SortTime (int xscale,int yscale, String graphTitle)
|
||||
{
|
||||
//create the graph object with the specified x-axis, y-axis, and title
|
||||
myGraph=new Graph(xscale, yscale, graphTitle);
|
||||
MAX=2*xscale;
|
||||
Random rand=new Random();
|
||||
|
||||
//create an array of CDs that have random titles for sorting
|
||||
original=new CD[MAX];
|
||||
originalSorted=new CD[MAX];
|
||||
|
||||
for (int y=0;y<original.length;y++)
|
||||
{
|
||||
String title="";
|
||||
for (int x=0;x<5;x++)
|
||||
{
|
||||
char myChar;
|
||||
int temp=Math.abs(rand.nextInt())%36;
|
||||
if (temp<10)
|
||||
{
|
||||
myChar=(char) (temp+48);
|
||||
}
|
||||
else
|
||||
{
|
||||
myChar=(char) (temp+87);
|
||||
}
|
||||
title=title+myChar;
|
||||
}
|
||||
original[y]=new CD(title,"Rush",12.99,11);
|
||||
}
|
||||
|
||||
for (int y=0;y<original.length;y++)
|
||||
{
|
||||
originalSorted[y]=original[y];
|
||||
}
|
||||
|
||||
//need a sorted version to test quicksort in the worst case
|
||||
SortRoutines.quickSort((Comparable[])originalSorted,0,original.length-1);
|
||||
}
|
||||
|
||||
public void doTask(Object[] myArray,int n,int choice)
|
||||
{
|
||||
switch (choice)
|
||||
{
|
||||
//here is where we call the various sorting techniques
|
||||
//explain why the parameter lists appear as they do
|
||||
case 1:
|
||||
SortRoutines.selectionSort((Comparable[])myArray,n);
|
||||
break;
|
||||
case 2:
|
||||
SortRoutines.insertionSort((Comparable[])myArray,n);
|
||||
break;
|
||||
case 3:
|
||||
SortRoutines.bubbleSort((Comparable[])myArray,n);
|
||||
break;
|
||||
case 4:
|
||||
SortRoutines.mergeSort((Comparable[])myArray,0,n-1);
|
||||
break;
|
||||
case 5:
|
||||
SortRoutines.quickSort((Comparable[])myArray,0,n-1);
|
||||
break;
|
||||
case 6:
|
||||
SortRoutines.radixSort((Radixable[])myArray, 4, n);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void go (int start,int stop, int step, String title, Color myColor, int choice)
|
||||
{
|
||||
sorted=new CD[MAX];
|
||||
|
||||
//creates a new set of data with the specified color
|
||||
DataVector myData=new DataVector(title,myColor);
|
||||
myGraph.addData(myData);
|
||||
|
||||
//prevents array overflow (can't go higher than MAX)
|
||||
//otherwise the user could ask for a simulation range larger than the array can support
|
||||
if (stop>myGraph.getX()*2)
|
||||
stop=myGraph.getX()*2;
|
||||
|
||||
//start over with an unsorted array, but the number of items to sort will increase
|
||||
for (int i=start; i<stop; i+=step)
|
||||
{
|
||||
//start again with an unsorted array
|
||||
for (int x=0;x<original.length;x++)
|
||||
{
|
||||
//switch the comments below to test quicksort worst case
|
||||
sorted[x]=original[x];
|
||||
//sorted[x]=originalSorted[x];
|
||||
}
|
||||
//try to garbage collect the old array that is no longer being used
|
||||
System.gc();
|
||||
|
||||
//here is the actual timing calculation
|
||||
long startTime=System.currentTimeMillis();
|
||||
doTask(sorted,i,choice);
|
||||
long stopTime=System.currentTimeMillis();
|
||||
int time=(int) (stopTime-startTime);
|
||||
|
||||
//add a point to the data set
|
||||
myData.addPoint(i, time);
|
||||
|
||||
//if we exceed the boundaries of the graph, reset Graph scale
|
||||
if (i > myGraph.getX())
|
||||
myGraph.setX(i + i/10);
|
||||
if (time > myGraph.getY())
|
||||
myGraph.setY(time + time/20);
|
||||
|
||||
//show the updated graph
|
||||
myGraph.repaint();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
//set up the graph with the x-range, y-range, and title
|
||||
SortTime timer=new SortTime(10000,2000,"Sorting Times");
|
||||
|
||||
//run simulations for various sorting techinques
|
||||
//starting number to sort, ending number to sort, step size for simulation, title of set of points, color of set of points, sorting algorithm to use (see above)
|
||||
timer.go(1,1900,100,"Selection",Color.blue,1);
|
||||
timer.go(1,1900,100,"Insertion",Color.red,2);
|
||||
timer.go(1,1900,100,"Bubble",Color.yellow,3);
|
||||
|
||||
timer.go(1,5000,100,"Merge",Color.green,4);
|
||||
timer.go(1,10000,100,"Quick",Color.white,5);
|
||||
timer.go(1,10000,100,"Radix",Color.gray,6);
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue