560 likes | 702 Views
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
E N D
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, …
Lists Analogies Egg carton Apartments Cassette carrier
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
Operations on Lists Fundamental list operations: Insertion Searching Deletion
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)
Basic Array Definition int [] intArray; // array declaration // // creating array object intArray = new int [100]; // Subscripts are 0 through 99
Sample Definitions Suppose int 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 ints char[] B = new char [MaxStringSize]; // 80 chars float[] = new C[M*N]; // array of 800 floats int[] Values = new int[MaxListSize]; //1000 ints Rational[] D = new Rational [N-15]; // 5 Rationals
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 0 A[0] Second element of list has index 1, and so on A[1] Last element has an index one less than the size of the list A[9] Incorrect indexing is a common error
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
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;
Extracting Values For A List int A = new int [MaxListSize]; int n = 0; int CurrentInput; while((n < MaxListSize)){ CurrentInput = getInt(); A[n] = CurrentInput; ++n; }
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!
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
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
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
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 Array Notice brackets are empty Could we just assign a 0 and have it work?
List Searching int Search (int List[], int m, int Key) { for (int i = 0; i < m; ++i) { if (List[i] == Key) { return i; } } return m; }
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
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
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
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]); } }
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
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
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
Important Discussion How 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
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
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
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
Deletion • Algorithm Efficiency (operation efficiency): • Time spent = ?
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): ?
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): ?
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
// display items for(int j=0; j<nElems; j++) System.out.print(arr[j] + " "); System.out.println("");
// 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
// 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
Key learning points: • Array declaration and initialization: long[] arr = new long[100]; // make array • Populate array: arr[0] = 77; // insert 10 item arr[1] = 99; • Array Length: nElems = 10; // now 10 items in array nElems = 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
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.
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
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
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
Another Object-oriented implementation (further improved)
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 }
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()
public void insert(long value) // put element into array { a[nElems] = value; // insert it nElems++; // increment size }
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()
public void display() // displays array contents { for(int j=0; j<nElems; j++) // for each element, System.out.print(a[j] + " "); // display it }
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