sorting & linked lists

Post on 13-May-2015

8.398 Views

Category:

Education

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

presentation

TRANSCRIPT

Sorting, Sorting, ADTs, ADTs,

Linked ListsLinked Lists

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?

SortingSorting

SortSort = 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 structstructs based on a 'key' field

(e.g. the .name.name field of the workerTworkerT structure we used in binary search)

SortingSorting

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 SortSelection SortCore Idea: Core Idea:

1.1. FindFind the item in list that shouldshould be first, How? for small-to-large ordering? large-to-

small?

2.2. SwapSwap it with the actualactual first item in the list remember the swap function? How did it work?

3.3. MoveMove a ‘wall’ or marker to separate the list into sorted and unsorted parts

4.4. RepeatRepeat on the unsorted part of the list untiluntil it disappears

Selection SortSelection Sort

1)1) FindFind smallest item in unsorted part of list

2)2) SwapSwap it with first item in the unsorted part of the list

3)3) MoveMove the ‘wall’ forward by one item, past sorted item

4)4) RepeatRepeat until the unsorted part of the list vanishes

Example: Example: small-to-large sortsmall-to-large sort

00

Selection Selection sortsort

Example: Example: small-to-large sortsmall-to-large sort

Selection Sort: Example Selection Sort: Example CodeCode

void SelSort(int lst[], int siz)void SelSort(int lst[], int siz){{int j, k, it, tmp;int j, k, it, tmp; /* sorted: 0/* sorted: 0jj

unsorted: j+1 unsorted: j+1siz-1siz-1 smallest unsorted: it smallest unsorted: it

*/*/

for(j=0; j<siz; j++)for(j=0; j<siz; j++) /* for all items on list *//* for all items on list */{{ it = j; it = j; /* (test item j first) *//* (test item j first) */ for(k=j+1; k<siz; k++) /* Search for min. item: */ for(k=j+1; k<siz; k++) /* Search for min. item: */ { { if(lst[k] < lst[it]) /*is ‘it’ smallest? */ if(lst[k] < lst[it]) /*is ‘it’ smallest? */ { { it = k; /* no—keep the smaller ‘k’ */ it = k; /* no—keep the smaller ‘k’ */ } } } /* Now ‘it’ is the smallest unsorted item. } /* Now ‘it’ is the smallest unsorted item. Swap ‘it’ and ‘j’ items*/ Swap ‘it’ and ‘j’ items*/ tmp = lst[j]; tmp = lst[j]; lst[j] = lst[it]; lst[j] = lst[it]; lst[it] = lst[tmp]; lst[it] = lst[tmp]; } }}}

Insertion SortInsertion Sort

Core Idea:Core Idea: As before, a ‘wall’‘wall’ separates list into sorted and

unsorted parts (sorted part is empty at first). 1)1) FindFind the 1st unsorted item (just past the ‘wall’)2)2) SearchSearch sorted list for 1st item’s proper position, 3)3) SwapSwap 1st item: Remove from the unsorted list,

and Insert into sorted list.4)4) RepeatRepeat until unsorted list is empty.

Insertion SortInsertion Sort

Rem

ove

Rem

oveIn

sert

Inse

rt

Insertion Insertion sortsortExampleExample

(1(1stst unsorted item unsorted itemis automatially theis automatially the 11stst sorted item) sorted item)

Abstract Data Types: Abstract Data Types: ADTADTss

(Recall) ‘data type’‘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, defined by the way you use it,

an

AAbstract bstract DData ata TTypeype (ADT)

Abstract Data Types: Abstract Data Types: ADTADTss

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 requiredrequired for this

‘daisy chain’ to work as sorted/unsorted list

kkcc ee ff ss vvgg qq

pBgnpBgn pEndpEndpSortEndpSortEnd

NULLNULL

ADTs: How to do itADTs: How to do it

The best ADTs are easy to use: 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 Users don’t want (or need) to know the details;details; Give them simple ‘interface’ functions to do the needed tasks (e.g. void void insert(pHere,pThis); insert(pHere,pThis); void remove(pThis); void remove(pThis); )

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

ADTsADTs

ADT

Data structure

Operations

Interface UsersUsers(you, and other (you, and other project programmers)project programmers)

ADT ExamplesADT Examples

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.

An ADT: Singly Linked ListAn ADT: Singly Linked List

A listlist 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 ‘nodenode’ is an item on a linked list

kkcc ee ff ss vvgg qq

pBgnpBgn pEndpEndpSortEndpSortEnd

NULLNULL

ADT: Linked ListsADT: Linked Lists

What defines a linked list?What defines a linked list?

Nodes have pointers to ‘link’ them togetherin 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

ADT: Singly Linked ListsADT: Singly Linked Lists

Each node of a singly linked list contains: a node value (could be a complex struct 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 tailhead 8 3 12 1 NULL

nodenode nodenode nodenode nodenode

ADT: Singly Linked ListsADT: Singly Linked Lists

How can we define a node structure? Simple Example:

typedef struct node typedef struct node

{{

struct node *pNext; struct node *pNext; /*Pointer-to-node*//*Pointer-to-node*/

int value;int value;

} nodeT;} nodeT;A little tricky here:A little tricky here:Recall: data type is Recall: data type is struct nodestruct node,,typedef renames it all as typedef renames it all as nodeTnodeT, , thus thus

member variable member variable pNextpNext is is a pointer-to-nodeT-type-objectsa pointer-to-nodeT-type-objects

ADT: Singly Linked ListsADT: Singly Linked Lists

Be sure you understand this:

typedef struct GoodNode typedef struct GoodNode

{{

struct GoodNode *pNext; struct GoodNode *pNext; /*Pointer-to-node*//*Pointer-to-node*/

int value;int value;

} nodeT;} nodeT;

typedef struct nodeT typedef struct nodeT

{{

nodeT *pNext; nodeT *pNext; /*Pointer-to-node*//*Pointer-to-node*/

int value;int value;

} nodeT;} nodeT;

This works!This works!

NO! THE NO! THE OBVIOUSOBVIOUS WAY DOESN’T WORK!WAY DOESN’T WORK!

Singly Linked ListsSingly Linked Lists

What does this program create?int main(void) int main(void)

{{

nodeT *pHead, *pNode1;nodeT *pHead, *pNode1;

pNode1 = (nodeT*)malloc(1*sizeof(nodeT));pNode1 = (nodeT*)malloc(1*sizeof(nodeT));

pNode1–>pNext = NULL;pNode1–>pNext = NULL;

pNode1–>value = 10;pNode1–>value = 10;

pHead = pNode1;pHead = pNode1;

return 0;return 0;

}} 10 NULLNULLpHeadpHead

ADT: Singly Linked ListsADT: Singly Linked Lists

Typical interface functions you will need to write for a singly linked list ADT:

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?

Singly Linked ListsSingly Linked Lists

To attach a newly-created nodea newly-created node at pNew pNew right after the pNow pNow

node: nextnext’ member of struct at pNewpNew

pNew–>pNext = pNow–>pNext;pNew–>pNext = pNow–>pNext;

Then point pNowpNow’s next member to pNewpNew.pNow–>next = pNew;pNow–>next = pNew;

8 12 1 NULL

10pNewpNew

pHeadpHead

pNowpNow

Singly Linked ListsSingly Linked Lists

To attach a newly-created nodea newly-created node at pNew pNew right after the pNow pNow

node: First set the `nextnext’ member of struct at pNewpNew

pNew–>pNext = pNow–>pNext;pNew–>pNext = pNow–>pNext;

Then point pNowpNow’s next member to pNewpNew.pNow–>next = pNew;pNow–>next = pNew;

8 12 1 NULL

10pNewpNew

pHeadpHead

pNowpNow

Singly Linked ListsSingly Linked Lists

To attach a newly-created nodea newly-created node at pNew pNew right after the pNow pNow node:

First set the `nextnext’ member of struct at pNewpNewpNew–>pNext = pNow–>pNext;pNew–>pNext = pNow–>pNext;

Then point pNowpNow’s next member to pNewpNew.pNow–>next = pNew;pNow–>next = pNew;

8 12 1 NULL

10pNewpNew

pHeadpHead

pNowpNow

top related