csis 3401 introduction to data structures and algorithms

56
CSIS 3401 Introduction CSIS 3401 Introduction to Data structures and to Data structures and algorithms algorithms

Upload: casey-perez

Post on 02-Jan-2016

54 views

Category:

Documents


1 download

DESCRIPTION

CSIS 3401 Introduction to Data structures and algorithms. Lists. Problem solving often requires that data be viewed as a list List may be one-dimensional or multidimensional Two list mechanisms Arrays Traditional and important because of legacy libraries Restrictions on its use - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSIS 3401 Introduction to Data structures and algorithms

CSIS 3401 Introduction to CSIS 3401 Introduction to Data structures and Data structures and

algorithmsalgorithms

Page 2: CSIS 3401 Introduction to Data structures and algorithms

Lists• Problem solving often requires that data

be viewed as a list– List may be one-dimensional or

multidimensional

• Two list mechanisms– Arrays

• Traditional and important because of legacy libraries• Restrictions on its use

– Container classes• First-class list representation• Common containers

– Vector, queue, stack, map, …

Page 3: CSIS 3401 Introduction to Data structures and algorithms

Lists• Analogies

– Egg carton– Apartments– Cassette carrier

Page 4: CSIS 3401 Introduction to Data structures and algorithms

Array Terminology• List is composed of elements• Elements in a list have a common name

– The list as a whole is referenced through the common name

• List elements are of the same type — the base type

• Elements of a list are referenced by subscripting or indexing the common name

Page 5: CSIS 3401 Introduction to Data structures and algorithms

Operations on Lists

Fundamental list operations:•Insertion•Searching•Deletion

Page 6: CSIS 3401 Introduction to Data structures and algorithms

Arrays• Language restrictions

– Subscripts are denoted as expressions within brackets: [ ]

– Base type can be any fundamental, library-defined, or programmer -defined type

– The index type is integer and the index range must be0 ... n-1

• where n is a programmer-defined constant expression.

– Parameter passing style• Always call by reference (no indication necessary)

Page 7: CSIS 3401 Introduction to Data structures and algorithms

Basic Array Definition

// Subscripts are 0 through 99

int [] intArray; // array declaration//// creating array objectintArray = new int [100];

Page 8: CSIS 3401 Introduction to Data structures and algorithms

Sample Definitions

• Supposeint N = 20;int M = 40;int MaxStringSize = 80;int MaxListSize = 1000;

• Then the following are all correct array definitions.int[] A = new int [10]; // array of 10 intschar[] B = new char [MaxStringSize]; // 80 charsfloat[] = new C[M*N]; // array of 800 floats

int[] Values = new int [MaxListSize]; //1000 intsRational[] D = new Rational [N-15]; // 5 Rationals

Page 9: CSIS 3401 Introduction to Data structures and algorithms

Subscripting• Suppose

int[] A = new int[10]; // array of 10 ints // A[0] to A[9]

• To access an individual element we must apply a subscript to list name A– A subscript is a bracketed expression

• The expression in the brackets is known as the index

– First element of list has index 0A[0]

– Second element of list has index 1, and so onA[1]

– Last element has an index one less than the size of the listA[9]

• Incorrect indexing is a common error

Page 10: CSIS 3401 Introduction to Data structures and algorithms

Array Elements• Suppose

int[] A = new int[10]; // array of 10 uninitialized ints

• To access an individual element we must apply a subscript to list name A

-- -- ----AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- ---- -- --

Page 11: CSIS 3401 Introduction to Data structures and algorithms

Array Element Manipulation• Consider

int i = 7, j = 2, k = 4;A[0] = 1;A[i] = 5;A[j] = A[i] + 3;A[j+1] = A[i] + A[0];A[A[j]] = 12;A[k] = 6;

-- 8 61AA[4] A[5] A[6]A[3]A[0] A[2] A[8] A[9]A[7]A[1]

-- -- 53 --12

Page 12: CSIS 3401 Introduction to Data structures and algorithms

Extracting Values For A List int A = new int [MaxListSize];

int n = 0;

int CurrentInput;

while((n < MaxListSize)){

CurrentInput = getInt();

A[n] = CurrentInput;

++n;

}

Page 13: CSIS 3401 Introduction to Data structures and algorithms

Smallest Value• Problem

– Find the smallest value in a list of integers

• Input– A list of integers and a value indicating the

number of integers

• Output– Smallest value in the list

• Note– List remains unchanged after finding the

smallest value!

Page 14: CSIS 3401 Introduction to Data structures and algorithms

Preliminary Design• Realizations

– When looking for value with distinguishing characteristics, need a way of remembering best candidate found so far

– Best written as a function - likely to be used often

• Design– Search array looking for smallest value

• Use a loop to consider each element in turn• If current element is smallest so far, then update smallest

value so far candidate

– When done examining all of the elements, the smallest value seen so far is the smallest value

Page 15: CSIS 3401 Introduction to Data structures and algorithms

Necessary Information• Information to be maintained

– Array with values to be inspected for smallest value

– Number of values in array– Index of current element being

considered– Smallest value so far

Page 16: CSIS 3401 Introduction to Data structures and algorithms

A More Detailed Design• Solution:

– Function that takes array of values and array size as its two in parameters; returns smallest value seen as its value

– Initialize smallest value so far to first element– For each of the other elements in the array

• If it is smaller than the smallest value so far, update the value the smallest value so far to current element

– Quit at end of array and return smallest value seen as value of function

Page 17: CSIS 3401 Introduction to Data structures and algorithms

int ListMinimum(const int A[], int asize) {int SmallestValueSoFar = A[0]; for (int i = 1; i < asize; ++i) {

if (A[i] < SmallestValueSoFar ) {SmallestValueSoFar = A[i];

}}return SmallestValueSoFar ;

}

Passing An ArrayNotice brackets are empty

Could we just assign a 0 and have it work?

Page 18: CSIS 3401 Introduction to Data structures and algorithms

List Searchingint Search (int List[], int m, int Key) {

for (int i = 0; i < m; ++i) {if (List[i] == Key) {

return i;

}

}

return m;

}

Page 19: CSIS 3401 Introduction to Data structures and algorithms

Sorting• Problem

– Arranging elements so that they are ordered according to some desired scheme• Standard is non-decreasing order

– Why don't we say increasing order?

• Major tasks– Comparisons of elements– Updates or element movement

Page 20: CSIS 3401 Introduction to Data structures and algorithms

Common Sorting Techniques

• Selection sort– On ith iteration place the ith smallest

element in the ith list location

• Bubble sort– Iteratively pass through the list and

examining adjacent pairs of elements and if necessary swap them to put them in order. Repeat the process until no swaps are necessary

Page 21: CSIS 3401 Introduction to Data structures and algorithms

Common Sorting Techniques• Insertion sort

– On ith iteration place the ith element with respect to the i-1 previous elements

• Quick sort– Divide the list into sublists such that every

element in the left sublist <= to every element in the right sublist. Repeat the Quick sort process on the sublists

Page 22: CSIS 3401 Introduction to Data structures and algorithms

SelectionSort

void SelectionSort(int A[], int asize) {for (int i = 0; i < asize-1; ++i) {

int ithMinSpot = i;

for (int j = i + 1; j < asize; ++j) {if (A[j] < A[ithMinSpot])

ithMinSpot = j;

}

if (i != ithMinSpot)swap(A[ithMinSpot], A[i]);

}

}

Page 23: CSIS 3401 Introduction to Data structures and algorithms

Complexity

• SelectionSort() Question– How long does the function take to run

• Proportional to n*n time units, where n is the number of elements in the list

• General question– How fast can we sort using the perfect

comparison-based method• The best possible worst case time is

proportional ton log n time units

Page 24: CSIS 3401 Introduction to Data structures and algorithms

• Basic concepts of arrays • A static data structure

• Most commonly used data structure

– Features:• Fixed size (length)• Same data type for all elements

– Generic Array Operations – Insert– Find (Search)– Delete

Page 25: CSIS 3401 Introduction to Data structures and algorithms

• Insertion

– Problem: • insert a new item into an array

– Algorithm:• By default, insertion will be done at the first empty cell• Another consideration (please consider it later)

– If an insertion index is specified, then the insertion will be performed at the specified position

– Data structure:• Input: an array with some elements & a new value• Output: an array with the new element inserted

Page 26: CSIS 3401 Introduction to Data structures and algorithms

Important DiscussionHow many logical steps needed to get insertion

operation done in terms of input size? (efficiency of the operation)

– The number of logical steps does NOT change with the number of items in the array: Constant time

Page 27: CSIS 3401 Introduction to Data structures and algorithms

• Search (Find)

– Problem: • find an element with specified value in the array• Another consideration

– Searching with Duplicates

– Algorithm:• Start from the first element… compare values…then

second element…compare values… till the element is found (value matching)

– Data structures:• Input: an array with some elements & a target value• Output: Boolean search result & index of found

element

Page 28: CSIS 3401 Introduction to Data structures and algorithms

Search

– How long (many logical steps) it takes to find the expected element?• Dynamic• Worse case: the number of elements in the

array• Then in theory: the logical steps it takes is

proportional to the length of the array• Computation time = K * N (N is the number

of elements in the array)– K is a coefficient

Page 29: CSIS 3401 Introduction to Data structures and algorithms

• Deletion

– Problem:• Delete an item with specified value in the array

– Deletion with duplicates (please consider later)

– Algorithm:• Figure 2.2 (P37)

– Data Structures:• Input: array, value• Output:

– Boolean deletion result– Array with possible change

Page 30: CSIS 3401 Introduction to Data structures and algorithms

Deletion

– Algorithm Efficiency (operation efficiency):• Time spent = ?

Page 31: CSIS 3401 Introduction to Data structures and algorithms

• Searching with duplicates– Problem: find all items with the specified value– Algorithm:– Data structures:

• Output: multiple index values

– Algorithm Efficiency (Time Spent): ?

• Insertion with duplicates/Insertion with index specified– Algorithm:– Data structures:– Algorithm Efficiency (Time Spent): ?

Page 32: CSIS 3401 Introduction to Data structures and algorithms

Deletion with Duplicates

– Problem: delete every items with the specified value

– Algorithm:– Data structures

• Output: multiple elements with the specified value might be removed

– Algorithm Efficiency (Time Spent): ?

Page 33: CSIS 3401 Introduction to Data structures and algorithms

Array Implementation

Page 34: CSIS 3401 Introduction to Data structures and algorithms

class ArrayApp { public static void main(String[] args) { long[] arr = new long[100]; // create array int nElems = 0; // number of items long searchKey; // key of item to search for

arr[0] = 77; // insert 10 items arr[1] = 99; arr[2] = 44; arr[3] = 55; arr[4] = 22; arr[5] = 88; arr[6] = 11; arr[7] = 00; arr[8] = 66; arr[9] = 33;

nElems = 10; // now 10 items in array

Page 35: CSIS 3401 Introduction to Data structures and algorithms

// display items

for(int j=0; j<nElems; j++) System.out.print(arr[j] + " "); System.out.println("");

Page 36: CSIS 3401 Introduction to Data structures and algorithms

// find item with key 66

searchKey = 66; for(j=0; j<nElems; j++) // for each element, if(arr[j] == searchKey) // found item? break; // yes, exit before end if (j == nElems) // at the end? System.out.println("Can't find " + searchKey); // yeselse System.out.println("Found " + searchKey); // no

Page 37: CSIS 3401 Introduction to Data structures and algorithms

// delete item with key 55

searchKey = 55;

for(j=0; j<nElems; j++) // look for it if(arr[j] == searchKey) break; for(int k=j; k<nElems; k++) // move higher ones down arr[k] = arr[k+1];

nElems--; // decrement size

Page 38: CSIS 3401 Introduction to Data structures and algorithms

Key learning points:

– Array declaration and initialization:long[] arr = new long[100]; // make array

– Populate array:arr[0] = 77; // insert 10 itemarr[1] = 99;

– Array Length:nElems = 10; // now 10 items in arraynElems = arr.length; //return the length of array arr

– Array search (loop through array)for(j=0; j<nElems; j++) // for each element, if(arr[j] == searchKey) // found item? break; // yes, exit before end

Page 39: CSIS 3401 Introduction to Data structures and algorithms

• The previous program works and successfully demonstrates the operations (insertion, deletion, search) of Array data structure.

• However, the code (operations, insertion, deletion, search, display) cannot be easily reused, basically, it is based on the traditional procedural approach, not objected-oriented approach.

• We need transform the code into more object-oriented program.

Page 40: CSIS 3401 Introduction to Data structures and algorithms

Objected-Oriented Implementation

Page 41: CSIS 3401 Introduction to Data structures and algorithms

class LowArray { private long[] a; // ref to array a

public LowArray(int size) // constructor { a = new long[size]; } // create array public void setElem(int index, long value) // set value { a[index] = value; } public long getElem(int index) // get value { return a[index]; } } // end class LowArray

Page 42: CSIS 3401 Introduction to Data structures and algorithms

class LowArrayApp { public static void main(String[] args) { LowArray arr; // reference arr = new LowArray(100); // create LowArray object int nElems = 0; // number of items in array int j; // loop variable

arr.setElem(0, 77); // insert 10 items arr.setElem(1, 99); arr.setElem(2, 44); arr.setElem(3, 55); arr.setElem(4, 22); arr.setElem(5, 88); arr.setElem(6, 11); arr.setElem(7, 00); arr.setElem(8, 66); arr.setElem(9, 33); nElems = 10; // now 10 items in array

for(j=0; j<nElems; j++) // display items System.out.print(arr.getElem(j) + " "); System.out.println("");

//continued next page

Page 43: CSIS 3401 Introduction to Data structures and algorithms

int searchKey = 26; // search for data item for(j=0; j<nElems; j++) // for each element, if(arr.getElem(j) == searchKey) // found item? break; if(j == nElems) // no System.out.println("Can't find " + searchKey); else // yes System.out.println("Found " + searchKey);

// delete value 55 for(j=0; j<nElems; j++) // look for it if(arr.getElem(j) == 55) break; for(int k=j; k<nElems; k++) // higher ones down arr.setElem(k, arr.getElem(k+1) ); nElems--; // decrement size

for(j=0; j<nElems; j++) // display items System.out.print( arr.getElem(j) + " ");

} // end main() } // end class LowArrayApp

Page 44: CSIS 3401 Introduction to Data structures and algorithms

Another Object-oriented implementation(further improved)

Page 45: CSIS 3401 Introduction to Data structures and algorithms

class HighArray { private long[] a; // ref to array a private int nElems; // number of data items

public HighArray(int max) // constructor { a = new long[max]; // create the array nElems = 0; // no items yet }

Page 46: CSIS 3401 Introduction to Data structures and algorithms

• public boolean find(long searchKey) { // find specified value int j; for(j=0; j<nElems; j++) // for each element, if(a[j] == searchKey) // found item? break; // exit loop before end if(j == nElems) // gone to end? return false; // yes, can't find it else return true; // no, found it } // end find()

Page 47: CSIS 3401 Introduction to Data structures and algorithms

• public void insert(long value) // put element into array { a[nElems] = value; // insert it nElems++; // increment size }

Page 48: CSIS 3401 Introduction to Data structures and algorithms

public boolean delete(long value) { int j; for(j=0; j<nElems; j++) // look for it if( value == a[j] ) break; if(j==nElems) // can't find it return false; else // found it { for(int k=j; k<nElems; k++) // move higher ones down a[k] = a[k+1]; nElems--; // decrement size return true; } } // end delete()

Page 49: CSIS 3401 Introduction to Data structures and algorithms

public void display() // displays array contents { for(int j=0; j<nElems; j++) // for each element, System.out.print(a[j] + " "); // display it }

Page 50: CSIS 3401 Introduction to Data structures and algorithms

class HighArrayApp { public static void main(String[] args) { int maxSize = 100; // array size HighArray arr; // reference to array arr = new HighArray(maxSize); // create the array

arr.insert(77); // insert 10 items arr.insert(99); arr.insert(44); arr.insert(55); arr.insert(22); arr.insert(88); arr.insert(11); arr.insert(00); arr.insert(66); arr.insert(33);

arr.display(); // display items

int searchKey = 35; // search for item if( arr.find(searchKey) ) System.out.println("Found " + searchKey); else System.out.println("Can't find " + searchKey);

arr.delete(00); // delete 3 items arr.delete(55); arr.delete(99);

arr.display(); // display items again } // end main() } // end class HighArrayApp

Page 51: CSIS 3401 Introduction to Data structures and algorithms

Other issues

Page 52: CSIS 3401 Introduction to Data structures and algorithms

• The Abstract Data type (ADT)– a specification of a set of data and the set of operations

that can be performed on the data structure

– AbstractDataType Array {Instances

Set of (index, value) pairs, no two pairs have the same index

Operations:Create: create an empty arrayInsert (value): add the new value into the array as the last

elementInsert (index, value): add the new value into the array at a

specified indexDelete (value): delete the item with the specified value from the

arrayFind (value): search the item with the specified value in the array

}

Page 53: CSIS 3401 Introduction to Data structures and algorithms

• Two dimensional arrays– Each row of a two-dimensional array is a one-

dimensional array– In Java, a two-dimension array is an array of references

to array objects

– Java Example:

double[][] a;a = new double[100][9];

a[0][5] = 36.4;double b = a[0][5];int c = a[0].length;

Page 54: CSIS 3401 Introduction to Data structures and algorithms

• Exercise:

– Based on Class HighArray in the book, please build one more operation, InsertAtIndex(index, value), into class definition.

– Write a Java problem to test InsertAtIndex(index, value)

method.

Page 55: CSIS 3401 Introduction to Data structures and algorithms

ArrayList• A Java class• Dynamically grows and shrinks• The elements are references to

objects of class Object

Page 56: CSIS 3401 Introduction to Data structures and algorithms

import java.util.ArrayList;

public class Myclass{

Arraylist list = new ArrayList();list.add(“AAA”);list.add(“BBB”);

. . .

list.remove(3); // remove element with index 3}