Introduction

advertisement
CS 340 DATA
STRUCTURES
Instructor: Xenia Mountrouidou
CS150
2
Who am I?
• Dr. X – Computer Scientist
• PhD at North Carolina State University – Optical networks
performance
• Worked for IBM – Software Performance Engineer
• Post doc at College of William and Mary
• Scuba diver, manga comics collector, science fiction
reader.
CS150
Who am I?
3
CS 340
4
Course Objectives
• At the end of this class you will be able to:
• Make design decisions on which data structure is best to use
regarding
• performance,
• memory, and
• implementation efficiency.
• Devise or use the most efficient algorithm in your projects.
• Understand algorithmic complexity.
• Think analytically and identify complexity of a program.
CS 340
5
Course Objectives (cont.)
• At the end of this class you will be able to:
• Apply object oriented programming principles when you develop
software.
• Use and understand third party code.
• Detect inefficiency of data structures and algorithms of third party
code.
• Develop projects using agile test driven approach (Junit).
• Employ the Java API.
CS 340
6
Why do you need CS 340?
• Scenario:
• You are a senior developer for Amazon.
• You are working on their e-commerce application server!
• You are a java guru, OO programming is second nature to you…
but you do not understand data structures and algorithms.
• BIG DEAL! Everything runs perfectly. Until one day…
• You need to use a sorting algorithm to sort all potential sellers of a
product based on price or ranking or relevance.
CS 340
7
Why do you need CS 340?
• Scenario (cont.):
• On every click for a product search, your sorting algorithm will be
used.
• You choose bubble sort. After all, it has a cool name!
• Let’s see what happens:
• http://www.sorting-algorithms.com/
Software is not just coding…
It is design, performance, memory consumption
It is an art, a riddle to be solved with every project
CS 340
8
More motivation
• Social networks
• Do you know which data structures FB developers are using?
• Which data structure is better to use for a social network?
• Do you know how Google search works?
• What is the best algorithm and why?
• Do they use any data structures?
• Have you heard about Big Data?
CS 340
9
Lectures
• We meet at 11:00-12:45, every Tues/Thurs, at Merritt
Penticoff Science Bld, Room 116A
• Check the schedule on the class webpage
• Reading and examples will be posted online
• Lectures will be interactive. This means:
• You will need to study the new material before every lecture
(slides and book or online material)
• We will have a lab every week, you will need to code
• You will have a test every week:
• A couple of questions on last week’s topics
• A couple of questions about current week’s topics
CS 340
10
Lectures
• I will not talk more than half an hour (hopefully!)
• During lectures I will demonstrate coding
• Your questions are important!
• However, you should not interrupt the flow of class
• I will have specific slides/time during lecture or coding
when you can ask questions
CS 340
11
Electronic Devices
• You may use your laptop to take notes and complete
programming assignments during class
• You will use the classroom computers to take tests
• Smart phones will be on silent mode during class time
• You may record the lectures
CS 340
QUESTIONS?
12
CS 340
13
How to get help
• Join my office hours at MP 203 (2nd floor)
• Monday 1:00 - 3:00 pm,
• Tuesday 9:00-11:00 am, and
• Thursday 1:00-2:00 pm
• Use the tutoring sessions at the CS Society meetings
(schedule will be announced soon)
• Use the tutor’s office hours (schedule will be announced soon)
• Set an appointment with me via e-mail(xmountr at ju.edu)
• Use the textbooks:
•
Data Structures and Algorithm Analysis in Java, Mark Allen Weiss,
3rd Edition, Pearson
•
Thinking in Java, Bruce Eckel, 3rd Edition. Free E-Book and
textbook website.
• Experiment with code. It’s fun…
CS 340
14
Grading
Final exam
25%
Homework
20%
Programming projects
30%
Tests
25%
Total
100%
Homework and Programming Projects will be posted
online on BlackBoard and on the class website
 You will upload your completed assignments on
BlackBoard

CS 340
15
Programming Projects
• They involve
• Data Structures & Algorithms
• Design
• Coding
• Testing
• Debugging
• These will be done in pairs
• You need to send me an e-mail until the end of the second
week of classes with your team members
• I will assign teams if you do not find a team
• Each team member will evaluate his/her team mate
• Each team member will contribute equally to coding,
design, and testing
CS 340
Homework
• It will involve:
• Analytical thinking
• Computational thinking
• A little bit of math
• Homework will be completed individually
16
CS 340
17
Policies
• Cheating means “submitting, without proper attribution,
any computer code that is directly traceable to the
computer code written by another person.”
• Or even better:
• “Any form of cheating, including concealed notes during exams, copying or
allowing others to copy from an exam, students substituting for one
another in exams, submission of another person’s work for evaluation,
preparing work for another person’s submission, unauthorized
collaboration on an assignment, submission of the same or substantially
similar work for two courses without the permission of the professors.
Plagiarism is a form of Academic Misconduct that involves taking either
direct quotes or slightly altered, paraphrased material from a source
without proper citations and thereby failing to credit the original author.
Cutting and pasting from any source including the Internet, as well as
purchasing papers, are forms of plagiarism.”
• I give students a failing homework grade for any cheating.
• A second cheating attempt will be escalated
CS 340
18
Policies
• You may discuss homework problems with classmates,
after you have made a serious effort in trying the
homework on your own.
• You can use ideas from the literature (with proper
citation).
• You can use anything from the textbooks/notes.
• The code you submit must be written completely by
you.
CS 340
Policies
• Read the collaboration policy carefully.
• Late policy:
• 1% is reduced by every day the homework is late
19
CS 340
Principles of Pair Programming
20
CS 340
21
Principles of Pair Programming
• All I Really Need to Know about pair programming I
Learned in Kindergarten
• Share everything.
• Play fair.
• Don’t hit people.
• Put things back where you found them.
• Clean up your own mess.
• Don’t take things that aren’t yours.
• Say you’re sorry when you hurt somebody.
CS 340
22
Principles of Pair Programming
• Wash your hands before you eat.
• Flush.
• Warm cookies and cold milk are good for you.
• Live a balanced life – learn some and think some and draw and
•
•
•
•
paint and sing and
Dance and play and work every day some.
Take a nap every afternoon.
When you go out into the world, watch out for traffic, hold hands
and stick together.
Be aware of wonder.
CS 340
Programming
languages… a
bit of history
23
CS 340
24
Programming Language Evolution
• 1st generation: Machine language
• 2nd generation: Assembler
• 3rd generation: COBOL, FORTRAN, C, ALGOL,
BASIC, C, C++, C#, Pascal, Ada and … Java
• 4th generation: SQL, spreadsheets, Mathematica,
MATLAB, SAS
• 5th generation: (example, anyone?)
CS 340
25
Why So Many Languages?
• Bring the language “closer” to the problem.
• But 4GLs are typically focused on specialized domains
(e.g., relational databases).
• We want a language that is general purpose, yet can
easily be “tailored” to any domain.
CS 340
QUESTIONS?
26
15
Java vs C#
CS 340
CS440
Java vs C#
• Not so different from each other
• C# versus Java : syntactic differences
• C# versus Java : a developer's perspective
28
29
Java vs C#: Program Structure
Java
C#
package hello;
using System;
public class HelloWorld {
namespace Hello {
public class HelloWorld {
public static void Main(string[]
args) {
string name = "C#";
public static void main(String[] args) {
String name = "Java";
// See if an argument was passed
from the command line
if (args.length == 1)
name = args[0];
System.out.println("Hello, " +
name + "!");
}
}
// See if an argument was
passed from the command line
if (args.Length == 1)
name = args[0];
Console.WriteLine("Hello, " +
name + "!");
}
}
}
30
Java vs C#: Comments
Java
C#
// Single line
// Single line
/* Multiple
/* Multiple
line */
line */
/** Javadoc documentation comments /// XML comments on a single line
*/
/** XML comments on multiple lines
*/
31
Java vs C#: Data Types
Java
C#
Primitive Types
boolean
byte
char
short, int, long
float, double
Value Types
bool
byte, sbyte
char
short, ushort, int, uint, long, ulong
float, double, decimal
structures, enumerations
Reference Types
Object (superclass of all other classes)
String
arrays, classes, interfaces
Reference Types
object (superclass of all other
classes)
string
arrays, classes, interfaces, delegates
32
Java vs C#: Data Types
Java
C#
Conversions
Conversions
// int to String
int x = 123;
String y = Integer.toString(x); // y is
"123"
// int to string
int x = 123;
String y = x.ToString(); // y is "123"
// String to int
y = "456";
x = Integer.parseInt(y); // x is 456
// string to int
y = "456";
x = int.Parse(y);
// or x = Convert.ToInt32(y);
// double to int
double z = 3.5;
x = (int) z; // x is 3 (truncates decimal)
// double to int
double z = 3.5;
x = (int) z; // x is 3 (truncates
decimal)
33
Java vs C#: Constants
Java
C#
// May be initialized in a constructor
final double PI = 3.14;
const double PI = 3.14;
// Can be set to a const or a variable.
//May be initialized in a constructor.
readonly int MAX_HEIGHT = 9;
34
Java vs C#: Operators
Java
C#
Comparison
== < > <= >= !=
Comparison
== < > <= >= !=
Arithmetic
+ - * /
% (mod)
/ (integer division if both operands are
ints)
Math.Pow(x, y)
Arithmetic
+ - * /
% (mod)
/ (integer division if both operands
are ints)
Math.Pow(x, y)
Assignment
= += -= *= /= %= &= |= ^= <<=
>>= >>>= ++ --
Assignment
= += -= *= /= %= &= |= ^= <<=
>>= ++ --
Bitwise
& | ^ ~ << >> >>>
Bitwise
& | ^ ~ << >>
35
Java vs C#: Operators
Java
C#
Logical
&& || & | ^ !
Logical
&& || & | ^ !
Note: && and || perform short-circuit
logical evaluations
Note: && and || perform short-circuit
logical evaluations
String Concatenation
+
String Concatenation
+
CS 340
QUESTIONS?
36
37
Java vs C#: Choices
Java
C#
greeting = age < 20 ? "What's up?" :
"Hello";
greeting = age < 20 ? "What's up?" :
"Hello";
if (x < y)
System.out.println("greater");
if (x < y)
Console.WriteLine("greater");
if (x != 100) {
x *= 5;
y *= 2;
}
else
z *= 6;
if (x != 100) {
x *= 5;
y *= 2;
}
else
z *= 6;
38
Java vs C#: Choices
Java
C#
int selection = 2;
switch (selection) {
// Must be byte, short, int, char, or
enum
case 1: x++;
// Falls through to next case if no
break
case 2: y++; break;
case 3: z++; break;
default: other++;
}
string color = "red";
switch (color) {
// Can be any predefined type
case "red": r++; break;
// break is mandatory; no fallthrough
case "blue": b++; break;
case "green": g++; break;
default: other++; break;
// break necessary on default
}
39
Java vs C#: Loops
Java
C#
while (i < 10)
i++;
while (i < 10)
i++;
for (i = 2; i <= 10; i += 2)
System.out.println(i);
for (i = 2; i <= 10; i += 2)
Console.WriteLine(i);
do
i++;
while (i < 10);
do
i++;
while (i < 10);
for (int i : numArray) // foreach
construct
sum += i;
foreach (int i in numArray)
sum += i;
40
Java vs C#: Loops
Java
C#
// for loop can be used to iterate through
any Collection
import java.util.ArrayList;
// foreach can be used to iterate
through any collection
using System.Collections;
ArrayList<Object> list = new
ArrayList<Object>();
list.add(10); // boxing converts to
instance of Integer
list.add("Bisons");
list.add(2.3); // boxing converts to
instance of Double
ArrayList list = new ArrayList();
for (Object o : list)
System.out.println(o);
foreach (Object o in list)
Console.WriteLine(o);
list.Add(10);
list.Add("Bisons");
list.Add(2.3);
41
Java vs C#: Arrays
Java
C#
int nums[] = {1, 2, 3}; or
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++)
System.out.println(nums[i]);
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]);
String names[] = new String[5];
names[0] = "David";
string[] names = new string[5];
names[0] = "David";
float twoD[][] = new float[rows][cols];
twoD[2][0] = 4.5;
float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;
int[][] jagged = new int[3][];
jagged[0] = new int[5];
jagged[1] = new int[2];
jagged[2] = new int[3];
jagged[0][4] = 5;
int[][] jagged = new int[3][] {
new int[5], new int[2], new int[3]
};
jagged[0][4] = 5;
42
Java vs C#: Functions
Java
C#
// Return single value
int Add(int x, int y) {
return x + y;
}
// Return single value
int Add(int x, int y) {
return x + y;
}
int sum = Add(2, 3);
int sum = Add(2, 3);
// Return no value
void PrintSum(int x, int y) {
System.out.println(x + y);
}
// Return no value
void PrintSum(int x, int y) {
Console.WriteLine(x + y);
}
PrintSum(2, 3);
PrintSum(2, 3);
43
Java vs C#: Functions
Java
C#
// Primitive types and references are always
passed by value
void TestFunc(int x, Point p) {
// Pass by value (default), in/out-reference (ref),
and out-reference (out)
void TestFunc(int x, ref int y, out int z, Point
p1, ref Point p2) {
x++; y++; z = 5;
p1.x++;
// Modifying property of the object
p1 = null; // Remove local reference to object
p2 = null; // Free the object
}
x++;
p.x++;
object
p = null;
object
}
// Modifying property of the
// Remove local reference to
class Point {
public int x, y;
}
Point p = new Point();
p.x = 2;
int a = 1;
TestFunc(a, p);
class Point {
public int x, y;
}
Point p1 = new Point();
Point p2 = new Point();
p1.x = 2;
int a = 1, b = 1, c; // Output param doesn't need
initializing
TestFunc(a, ref b, out c, p1, ref p2);
Console.WriteLine("{0} {1} {2} {3} {4}",
a, b, c, p1.x, p2 == null); // 1 2 5 3 True
44
Java vs C#: Functions
Java
C#
// Accept variable number of arguments
int Sum(int ... nums) {
int sum = 0;
for (int i : nums)
sum += i;
return sum;
}
// Accept variable number of arguments
int Sum(params int[] nums) {
int sum = 0;
foreach (int i in nums)
sum += i;
return sum;
}
int total = Sum(4, 3, 2, 1); // returns 10
int total = Sum(4, 3, 2, 1); // returns 10
45
Java vs C#: Strings
Java
C#
// String concatenation
String school = "Harding ";
school = school + "University"; // school is
"Harding University"
// String concatenation
string school = "Harding ";
school = school + "University"; // school is
"Harding University"
// String comparison
// String comparison
String mascot = "Bisons";
string mascot = "Bisons";
if (mascot == "Bisons") // Not the correct if (mascot == "Bisons") // true
way to do string comparisons
if (mascot.equals("Bisons")) // true
if (mascot.Equals("Bisons")) // true
if (mascot.equalsIgnoreCase("BISONS"))
if (mascot.ToUpper().Equals("BISONS"))
// true
// true
if (mascot.CompareTo("Bisons") == 0) //
if (mascot.compareTo("Bisons") == 0) //
true
true
Console.WriteLine(mascot.Substring(2,
3)); // Prints "son"
System.out.println(mascot.substring(2, 5));
// Prints "son"
46
Java vs C#: Strings
Java
C#
// My birthday: Oct 12, 1973
java.util.Calendar c = new
java.util.GregorianCalendar(1973, 10, 12);
String s = String.format("My birthday: %1$tb
%1$te, %1$tY", c);
// My birthday: Oct 12, 1973
DateTime dt = new DateTime(1973, 10,
12);
// Mutable string
StringBuffer buffer = new StringBuffer("two
");
buffer.append("three ");
buffer.insert(0, "one ");
buffer.replace(4, 7, "TWO");
System.out.println(buffer); // Prints "one
TWO three"
string s = "My birthday: " +
dt.ToString("MMM dd, yyyy");
// Mutable string
System.Text.StringBuilder buffer = new
System.Text.StringBuilder("two ");
buffer.Append("three ");
buffer.Insert(0, "one ");
buffer.Replace("two", "TWO");
Console.WriteLine(buffer); // Prints "one
TWO three"
CS 340
QUESTIONS?
47
48
Java vs C#: Exception Handling
Java
C#
// Must be in a method that is declared to
throw this exception
Exception ex = new Exception("Something is
really wrong.");
throw ex;
Exception up = new Exception("Something
is really wrong.");
throw up; // ha ha
try {
y = 0;
x = 10 / y;
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
// Code that always gets executed
}
try {
y = 0;
x = 10 / y;
} catch (Exception ex) {
// Variable
"ex" is optional
Console.WriteLine(ex.Message);
} finally {
// Code that always gets executed
}
49
Java vs C#: Namespaces
Java
C#
package harding.compsci.graphics;
namespace Harding.Compsci.Graphics {
...
}
or
// Import single class
import
harding.compsci.graphics.Rectangle;
namespace Harding {
namespace Compsci {
namespace Graphics {
...
}
}
}
// Import single class
using Rectangle =
Harding.CompSci.Graphics.Rectangle;
// Import all classes
// Import all class
using Harding.Compsci.Graphics;
50
Java vs C#: Classes / Interfaces
Java
C#
Accessibility keywords
public
private
protected
static
Accessibility keywords
public
private
internal
protected
protected internal
static
// Inheritance
class FootballGame extends Competition {
...
}
// Inheritance
class FootballGame : Competition {
...
}
51
Java vs C#: Classes / Interfaces
Java
C#
// Interface definition
interface IAlarmClock {
...
}
// Interface definition
interface IAlarmClock {
...
}
// Extending an interface
interface IAlarmClock extends IClock {
...
}
// Extending an interface
interface IAlarmClock : IClock {
...
}
// Interface implementation
class WristWatch implements IAlarmClock,
ITimer {
...
}
// Interface implementation
class WristWatch : IAlarmClock, ITimer {
...
}
52
Java vs C#: Constructors / Destructors
Java
C#
class SuperHero {
private int mPowerLevel;
class SuperHero {
private int mPowerLevel;
public SuperHero() {
mPowerLevel = 0;
}
public SuperHero() {
mPowerLevel = 0;
}
public SuperHero(int powerLevel) {
this.mPowerLevel= powerLevel;
}
public SuperHero(int powerLevel) {
this.mPowerLevel= powerLevel;
}
// No destructors, just override the
finalize method
protected void finalize() throws Throwable {
super.finalize(); // Always call parent's
finalizer
}
}
~SuperHero() {
// Destructor code to free unmanaged
resources.
// Implicitly creates a Finalize method.
}
}
53
Java
vs
C#:
Objects
Java
C#
SuperHero hero = new SuperHero();
SuperHero hero = new SuperHero();
hero.setName("SpamMan");
hero.setPowerLevel(3);
hero.Name = "SpamMan";
hero.PowerLevel = 3;
hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method
hero.Defend("Laura Jones");
SuperHero.Rest(); // Calling static method
SuperHero hero2 = hero; // Both refer to same
object
hero2.setName("WormWoman");
System.out.println(hero.getName()); // Prints
WormWoman
SuperHero hero2 = hero; // Both refer to same
object
hero2.Name = "WormWoman";
Console.WriteLine(hero.Name); // Prints
WormWoman
hero = null; // Free the object
hero = null; // Free the object
if (hero == null)
hero = new SuperHero();
if (hero == null)
hero = new SuperHero();
Object obj = new SuperHero();
System.out.println("object's type: " +
obj.getClass().toString());
if (obj instanceof SuperHero)
System.out.println("Is a SuperHero object.");
Object obj = new SuperHero();
Console.WriteLine("object's type: " +
obj.GetType().ToString());
if (obj is SuperHero)
Console.WriteLine("Is a SuperHero object.");
54
Java vs C#: Properties
Java
C#
private int mSize;
private int mSize;
public int getSize() { return mSize; }
public int Size {
get { return mSize; }
set {
if (value < 0)
mSize = 0;
else
mSize = value;
}
}
public void setSize(int value) {
if (value < 0)
mSize = 0;
else
mSize = value;
}
int s = shoe.getSize();
shoe.setSize(s+1);
shoe.Size++;
55
Java vs C#: Console I/O
Java
java.io.DataInput in = new
java.io.DataInputStream(System.in);
System.out.print("What is your name? ");
String name = in.readLine();
System.out.print("How old are you? ");
int age = Integer.parseInt(in.readLine());
System.out.println(name + " is " + age + "
years old.");
C#
Console.Write("What's your name? ");
string name = Console.ReadLine();
Console.Write("How old are you? ");
int age =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine(name + " is " + age + "
years old.");
int c = System.in.read(); // Read single
char
System.out.println(c);
// Prints 65 if user
enters "A"
int c = Console.Read(); // Read single char
Console.WriteLine(c); // Prints 65 if user
enters "A"
// The studio costs $499.00 for 3 months.
System.out.printf("The %s costs $%.2f for
%d months.%n", "studio", 499.0, 3);
// The studio costs $499.00 for 3 months.
Console.WriteLine("The {0} costs {1:C} for
{2} months.\n", "studio", 499.0, 3);
// Today is 06/25/04
System.out.printf("Today is %tD\n", new
java.util.Date());
// Today is 06/25/2004
Console.WriteLine("Today is " +
DateTime.Now.ToShortDateString());
56
Java vs C#: File I/O
Java
C#
import java.io.*;
using System.IO;
// Character stream writing
FileWriter writer = new
FileWriter("c:\\myfile.txt");
// Character stream writing
StreamWriter writer =
File.CreateText("c:\\myfile.txt");
writer.WriteLine("Out to file.");
writer.Close();
writer.write("Out to file.\n");
writer.close();
// Character stream reading
FileReader reader = new
FileReader("c:\\myfile.txt");
BufferedReader br = new
BufferedReader(reader);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
// Character stream reading
StreamReader reader =
File.OpenText("c:\\myfile.txt");
string line = reader.ReadLine();
while (line != null) {
Console.WriteLine(line);
line = reader.ReadLine();
}
reader.Close();
CS 340
QUESTIONS?
57
CS440
58
References
• C# versus Java : syntactic differences
http://www.harding.edu/fmccown/java_csharp_compariso
n.html
Download