CS110_09c_sortLinkList

# CS110_09c_sortLinkList - EECS110 9c Sorting ADTs Linked...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: EECS110: 9c Sorting, ADTs, Linked Lists Jack Tumblin [email protected] I hope you: Will soon prepare your final exam `cheat sheet'... Object-Oriented Practice 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 struct (e.g. the .name field of the workerT structure we used in binary search) Sorting Many sorting algorithms. One is built-in to C: `quicksort()' (try it!) We will discuss only two simple methods: selection sort insertion sort Demonstrate sorting items in fixed arrays, BUT sorts within dynamically-allocated memory are far more common. (and just as easy) 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 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' insert 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' insert 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 c e f g s v k q NULL Abstract Data Types: ADTs (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 would we call this `daisy chain' idea? it is made of dynamically-allocated structs and pointers It is a data type defined by the way you use it, an Abstract Data Type (ADT) Abstract Data Types: ADTs An ADT is defined by BOTH its structure, and a set of operations (e.g. 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 c e f g s v k q NULL ADTs: How to do it 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 needed tasks (e.g. void insert(pHere,pThis); 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! ADTs ADT Data structure Interface Operations Users (you, and other project programmers) ADT Examples lists (sequential order, but easy insert/remove) queues (first-come, first-served structures) stacks (last-in, first-out; like a stack of dishes) 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 List pBgn pSortEnd pEnd c e f g s v k q NULL A list is a sequential data collection without any intrinsic numbering. Does NOT require sequential memory locations Much more general & flexible than a fixed array Each list item can have different type(!) CS Jargon: a `node' is an item on a linked list node ADT: Linked Lists What defines 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: dynamic the number of nodes can change, AND the arrangement of nodes can change ADT: Singly Linked Lists Each node of a singly linked list contains: a node value (could be complex, a struct with many members) 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; directional must always move from head to tail node node node node head 8 3 12 1 NULL ADT: Singly Linked Lists How can we define a node structure? Simple Example: typedef struct node { struct node *pNext; int value; } nodeT; A little // Pointer-to-node 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 ADT: Singly Linked Lists Be sure you understand this: typedef struct GoodNode { struct GoodNode *pNext; int value; } nodeT; typedef struct GoodNode { nodeT *pNext; int value; NO! THE } nodeT; This works! // Pointer-to-node // Pointer-to-node OBVIOUS WAY DOESN'T WORK! Singly Linked Lists What does this program create? int main(void) { nodeT *pHead, *pNode1; pNode1 = (nodeT*)malloc(1*sizeof(nodeT)); pNode1>pNext = NULL; pNode1>value = 10; pHead = pNode1; return 0; } pHead 10 NULL ADT: 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 Lists: insert() 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 pNew pNow>next = pNew; pNow pHead 8 12 1 NULL pNew 10 Singly Linked Lists: insert() 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 pNew pNow>next = pNew; pNow pHead 8 12 1 NULL pNew 10 Singly Linked Lists: insert() 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 pNew pNow>next = pNew; pNow pHead 8 12 1 NULL pNew 10 ...
View Full Document

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern