Pointers - PowerPoint

Document Sample

```					    CS110: Lecture 25
Jack Tumblin
jet@cs.northwestern.edu

I hope you:
–   Are nearly done with Proj 5: Due Wed Dec. 4
–   Will soon prepare for final exam...
No New Material This Week
• Lets write a practice program...
– make a personT struct with name, ID#
– make some functions: (make stubs first)
• newPerson(personT *nu) – ask user for her info...
• swap(personT *a, personT *b); exchange contents
• isSorted(personT *a, personT *b)
TRUE if person 'a' is before 'b' alphabetically
• Gather entries in an array. Can we sort it?
Sorting
• Sort = arrange data according to its values
• Closely related to the search problem.
• Example:
– arrange numbers in largest-to-smallest order
– arrange names in alphabetical order
– arrange structs based on a 'key' field
(e.g. the .name field of the workerT structure
we used in binary search)
Sorting

• Many sorting algorithms;
We will discuss only two simple methods:
– selection sort
– insertion sort

• Demonstrate sorting items in arrays BUT
sorts within dynamically-allocated memory
are far more common.
Selection Sort
Core Idea:
1. Find the item in list that should be first,
•   How? for small-to-large ordering? large-to-small?

2. Swap it with the actual first item in the list
•   remember the swap function? How did it work?

3. Move a „wall‟ or marker to separate the list
into sorted and unsorted parts

4. Repeat on the unsorted part of the list
until it disappears
Selection Sort
Example:
small-to-large sort

0

1) Find smallest item in unsorted part of list
2) Swap it with first item in the unsorted part of the list
3) Move the „wall‟ forward by one item, past sorted item
4) Repeat until the unsorted part of the list vanishes
Selection sort

Example:
small-to-large sort
Selection Sort: Example Code
void SelSort(int lst[], int siz)
{
int j, k, it, tmp;               /* sorted: 0j
unsorted: j+1siz-1
smallest unsorted: it   */

for(j=0; j<siz; j++)           /* for all items on list */
{
it = j;                    /* (test item j first)    */
for(k=j+1; k<siz; k++)     /* Search for min. item: */
{
if(lst[k] < lst[it])   /*is ‘it’ smallest?       */
{
it = k;           /* no—keep the smaller ‘k’ */
}
}           /* Now ‘it’ is the smallest unsorted item.
Swap ‘it’ and ‘j’ items*/
tmp = lst[j];
lst[j] = lst[it];
lst[it] = lst[tmp];
}
}
Insertion Sort
Core Idea:
As before, a ‘wall’ separates list into sorted and
unsorted parts (sorted part is empty at first).

1) Find the 1st unsorted item (just past the „wall‟)

2) Search sorted list for 1st item‟s proper position,

3) Swap 1st item: Remove from the unsorted list,
and Insert into sorted list.

4) Repeat until unsorted list is empty.
Insertion Sort

Remove
Insert
(1st unsorted item
is automatially the
1st sorted item)

Insertion sort
Example
Insertion Sort: Example Code?

PROBLEM 1: Where to put item in sorted list:
Use binary search! (see prev. lecture)
0   1   2   3   4   5   6   7

c e f g s v k q

PROBLEM 2:
What is the best way to „insert‟ and „remove‟
an element from a list?
–If list is an array of structs, MESSY (lots of copying)
–If list is array of pointers-to-structs? also messy...
Insertion Sort: Example Code?
0   1   2   3    4   5     6   7

c e f g s v k q

•What is the best way to „insert‟ and „remove‟
an element from a list?
•We need something more flexible than arrays;
something WITHOUT strict element numbering

Core Idea: structs in a „daisy chain‟ of pointers...

pBgn                           pSortEnd           pEnd

NULL
c    e   f       g       s        v         k     q

• (Recall) ‘data type’ determines
the set of all possible values for a variable.
• Data types defined by C language syntax:
– basic data types: int, char, float, double
– derived data types: arrays, pointers, structs, and their
constructions (e.g. array of int, pointer to float)

• But what is this „daisy chain‟?
– it is made of dynamically-allocated structs and pointers
– It is a data type defined by the way you use it, an
• An ADT is defined by BOTH
– its structure, and
– a set of operations (functions) that control it.

• Structure alone isn‟t enough. EXAMPLE:
– Setting pointers properly is required for this
„daisy chain‟ to work as sorted/unsorted list

pBgn                   pSortEnd       pEnd

NULL
c   e   f   g   s      v       k     q
• The best ADTs are easy to use:
they „hide the details‟ from user with
well-chosen functions and structures.
• Users don’t want (or need) to know the details;
Give them simple „interface‟ functions to do the
void remove(pThis);           )

• Good strategy for large programming projects:
If the function prototypes do not change, then
(e.g. „the interface‟, or .h file) then the function‟s
author can improve, repair, upgrade it without
changing any programs/code that use it!

Data structure
Interface
Users
Operations                   (you, and other
project programmers)
•   lists (sequential order, but easy insert/remove)
•   queues (first-come, first-served structures)
•   stacks (last-in, first-out; like a stack of paper)
•   dynamic sets (a collection of objects, no ordering)
•   graphs (trees, networks of connected nodes)

„Interface‟ functions often include:
–   “create new item,”
–   “delete/remove this item,”
–   “get next item,”
–   “push an item onto stack,”
–   “pop an item off of the stack,” etc.
pBgn                   pSortEnd       pEnd

NULL
c    e   f   g   s      v       k     q

• A list is a sequential data collection
without any intrinsic numbering.
– Does NOT require sequential memory locations
– Much more general, flexible than array
• Each list item can have different type(!)
• CS Jargon: a „node‟ is an item on a linked list

• Nodes have pointers to „link‟ them together
in a linear, chain-like arrangement.
• A list is linear : each node has exactly one
„parent‟ and exactly one „child‟
• Changing pointers makes a list dynamic:
– the number of nodes can change, AND
– the arrangement of nodes can change
• Each node of a singly linked list contains:
– a node value (could be a complex   struct...)

– a pointer to the next node.
• The last node on the list points to NULL (tail).
• We also need a pointer for the list start (head).
• Singly linked lists are one-directional;
must always move from head to tail
node     node    node       node
head      8        3       12         1          NULL
• How can we define a node structure?
Simple Example:

typedef struct node
{
struct node *pNext;          /*Pointer-to-node*/
int value;
} nodeT;           A little tricky here:
Recall: data type is struct node,
typedef renames it all as nodeT, thus

member variable pNext is
a pointer-to-nodeT-type-objects
• Be sure you understand this:
typedef struct GoodNode                This works!
{
struct GoodNode *pNext;   /*Pointer-to-node*/
int value;
} nodeT;

typedef struct nodeT
{
nodeT *pNext;           /*Pointer-to-node*/
int value;
} nodeT;        NO! THE OBVIOUS WAY
DOESN’T WORK!
What does this program create?
int main(void)
{

pNode1 = (nodeT*)malloc(1*sizeof(nodeT));
pNode1–>pNext = NULL;
pNode1–>value = 10;
return 0;
}

• Typical interface functions you will need to write for

–   insert - add an element to the list
–   delete - remove an element from the list
–   isEmpty - find out if the list is empty
–   printList - traverse and display the list.

• How would you write the „isEmpty‟ function?
• The „insert‟ function?
– To attach a newly-created node at pNew
right after the pNow node:
– First set the `next‟ member of struct at pNew
pNew–>pNext = pNow–>pNext;
– Then point pNow‟s next member to pNew.
pNow–>next = pNew;

pNow

pNew     10
– To attach a newly-created node at pNew
right after the pNow node:
– First set the `next‟ member of struct at pNew
pNew–>pNext = pNow–>pNext;
– Then point pNow‟s next member to pNew.
pNow–>next = pNew;

pNow

pNew     10
– To attach a newly-created node at pNew
right after the pNow node:
– First set the `next‟ member of struct at pNew
pNew–>pNext = pNow–>pNext;
– Then point pNow‟s next member to pNew.
pNow–>next = pNew;

pNow