Lecture 3 Data Structures

Lecture 3 Data Structures

Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 1 Data Structures and Algorithms Programs. Different problems. Operations. Size of data. Resources available.

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2 Overview of Lecture Basic data structures. How to manipulate them. How to implement them. Other algorithms and how to implement them. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 3

This Lecture - Review Basic C data types Boolean 1D and multidimensional arrays Strings Input/Output File I/O Structures and typedef copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 4 Basic Data types in C

int char float double copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 5 Boolean Has two values, true and false. In C we use integers as Booleans.

Zero represents false. Any non-zero integer represents true. The library contains definition for bool, true, and false. (This doesnt work in Borland) In Borland programs, use #define to define the constants true and false copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 6 #include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; }

} For Borland use #define or const int #define true 1 #define false 0 int leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } } Recall: File inclusion header #include bool leapYear(int year) {

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } } Recall: Function definition #include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; }

else { return false; } } Recall: #include Function name bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } else { return false; } }

Recall: Function return type #include bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; } Must be compatible with else the functions return type { return true; } } Recall: #include

bool leapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ) { return true; Function parameter } else { Parameter type return false; } } Recall: int main() { int year, month, day; printf(Enter year, month and day: ); scanf(%d %d %d, &year, &month, &day); day = dayOfYear(year, month, day); printf(\nDay of Year = %d\n, day);

} Function call Review - Arrays (1D) array1D: 0 1 N-1 All the elements are of the same type. An element: array1D[index] In C, the first element has index 0 (zero). copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 15 Review - Multidimensional Arrays array2D:

Arrays of arrays. All the elements are of the same type. An element:copyarray2D[row][column] right (version1.0) SUNITHA C.N,CS&E dept,SJCE 16 int dayTable[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; int dayOfYear(int year, int month, int day) { int i; int isLeap = leapYear(year); for (i = 1; i < month; i++) { day += dayTable[isLeap][i]; } return day; }

Recall: int dayTable[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; Global variable int dayOfYear(int year, int month, int day) { Local variable int i; int isLeap = leapYear(year); for (i = 1; i < month; i++) { day += dayTable[isLeap][i]; } return day; } Recall: int dayTable[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

}; int dayOfYear(int year, int month, int day) { 2-dimensional array int i; int isLeap = leapYear(year); for (i = 1; i < month; i++) { day += dayTable[isLeap][i]; } return day; } of int Recall: int dayTable[2][13] = { {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} }; Index goes from 0 to 12 int dayOfYear(int year, int month, int day) {

int i; int isLeap = leapYear(year); for (i = 1; i < month; i++) { day += dayTable[isLeap][i]; } return day; } Review Input/Output Input/Output is done via streams Uses the library stdio.h Streams that are available in the library are stdin (keyboard), stdout and stderr (screen). These can be redirected. Data is written to stdout using the printf() function. printf("%s\n%f\n%c\n%d\n", name, age, gender, idNumber); Format control string Variables containing data to be printed Data is read in from stdin using the scanf() function. scanf("%s %f %c %d", name, &age, &gender, &idNumber); Conversion specifiers

copy right (version1.0) SUNITHA Pointers to variables where C.N,CS&E dept,SJCE 21 input will be stored Review Input/Output scanf() returns the number of values successfully read and converted or returns a special value EOF when input ends. Note for when reading a single character (%c): if there is a \n character left in the buffer from reading another value (%d) then that \n will be read into your character variable. Conversion specifiers: i or d: display a signed decimal integer f: display a floating point value

e or E: display a floating point value in exponential notation g or G: display a floating point value in either f form or e form L: placed before any float conversion specifier to indicate that a long double is displayed copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 22 #include int main() { int day; int month; int year; char name[30]; printf(Enter your name:\n> scanf(%s, name); Note: no ampersand for strings Conversion specifier

/* skipping spaces */ printf(Hi %s. Enter birthdate as: dd mm yyyy\n, name); scanf("%d %d %d", &day, &month, &year); Literal characters /* alternative */ printf(Hi %s. Enter birthdate as: dd-mm-yyyy\n, name); scanf("%d-%d-%d", &day, &month, &year); return 0; } Review - Strings Strings : array of characters Example: Max length including \ 0 char name[30]; Unlike other arrays, strings require an end-of-string character : \0 String functions you will use from the string.h library include:

Length - strlen(string1) Assignment - strcpy(dest, source) Copies string2 onto the end of the destination string Concatenation - strcat(dest, string2) Comparison - strcmp(string1, string2) Returns: positive if string1 sorts after string2, 0 if they are the same copy string right (version1.0) C.N,CS&E dept,SJCE negative if string1 sorts before string2 SUNITHA 24 #include #include

#define MAXLENGTH 100 int main() { char string1[MAXLENGTH]; char string2[MAXLENGTH]; strcpy(string1, Hello World!); strcpy(string2, string1); string1 needs to fit the number of characters of the second string, +1 for the \0 character string2 needs to be the same length as string 1 length = strlen(string1); printf(length of string1 = %d\n, length); strcpy(string1, Apple); strcpy(string2, Orange); if (strcmp(string1, string2) < 0)

{ printf(%s %s\n, string1, string2); } else if (strcmp(string1, string2) == 0) { printf(The strings are the same.\n); } else { printf(%s %s\n, string2, string1); } Prints the order which the two strings sort, alphabetically. strcat(string1, juice); printf(%s\n, string1); return 0; }

Note: To scan within a string use: sscanf(string1, %d, int1); Review -File Handling in C Files need to be opened before use. Associate a "file handler" to each file Modes: read, write, or append File input/output functions use the file handler (not the filename). Need to check the file opened sucessfully. Need to close the file after use. Basic file handling functions: fopen(), fclose(), fscanf(), fprintf(), fgets(). copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 27 #include #define MAXLEN 100 Associate a file handler for every

file to be used. int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; char name[MAXLEN]; int count; float mark; Mode r : read w : write a : append inputfile = fopen(Names.txt, r); outputfile = fopen(marks.dat, w); if (inputfile == NULL) { printf(Unable to open input file.\n); return 1; } if (outputfile == NULL)

{ printf(Unable to open output file.\n); return 1; } fopen() returns NULL if an error occurs count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; fscanf() returns the number of values read and converted printf("Enter mark for %s: \n", name); scanf("%f", &mark); if ( fprintf(outputfile, "%s %f\n", name, mark) <= 0 ) {

printf("Error writing to output file.\n"); fprintf() returns the number of return 1; } successfully } printf("\n"); printf("Number of names read: %d\n", count); fclose(inputfile); fclose(outputfile); } return 0; written or negative if an error occurs #include #define MAXLEN 100 To read in a line, use fgets(). fgets() returns NULL if end of file is reached.

int main() { FILE *inputfile = NULL; char line[MAXLEN]; int count = 0; inputfile = fopen(Names.txt, r); if (inputfile == NULL) { printf(Unable to open input file.\n); return 1; } fgets(string, length, filehandle) while(fgets(line, MAXLEN, inputfile) != NULL) { count++; } printf(Number of lines: %d, count); fclose(inputfile); return 0; }

What would happen if you tried to count the number of lines again, once the end of the file has been reached? Review - struct structname: Members may have different types. structname.membername structs are also known as records, and copy right (version1.0) SUNITHA members as fields C.N,CS&E dept,SJCE 31 Review - typedef Gives a new name to a type that has already been defined. E.g. typedef struct StudentRec Student;

Saves typing struct whatever everywhere. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 32 Example : #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; Recall: #include #define MAXNAME 80 Macro substitution

struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; Recall: #include Structure declaration #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; Recall:

#include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; Dont Structure name / tag Members forget this! typedef struct StudentRec Student; Recall: #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int

mark; }; Data type typedef struct StudentRec Student; New type name Student readStudent(void) { Student next; scanf(%s %d, next.name, &next.mark); return next; } void printStudent(Student student) { printf(%s %d\n, student.name, student.mark); } Recall: Student readStudent(void) {

Student next; An instance of the struct scanf(%s %d, next.name, &next.mark); return next; } Package A member of a struct variable void printStudent(Student student) { printf(%s %d\n, student.name, student.mark); } #define MAXCLASS 100 main() { Student class[MAXCLASS]; int n, i, best = 0; printf(Enter number of students: );

scanf(%d, &n); for (i = 0; i < n; i++) { class[i] = readStudent(); if (class[best].mark < class[i].mark) { best = i; } } printf(Best student is: ); printStudent(class[best]); } #define MAXCLASS 100 Array of instances of structs main() { Student class[MAXCLASS]; int n, i, best = 0; Recall: printf(Enter number of students: );

scanf(%d, &n); Assignment for (i = 0; i < n; i++) { class[i] = readStudent(); if (class[best].mark < class[i].mark) { best = i; } Member of an array element } printf(Best student is: ); printStudent(class[best]); } Revision Basic Data Types and booleans

I/O and File I/O Arrays and Structs Strings Typedef Preparation Next lecture: Pointers copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 42 Overview Revision of Pointers Basic Pointer Arithmetic Pointers and Arrays copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 43

Pointers A pointer is a datatype. You can create variables of this type as you would of other types. Contains a memory address. Points to a specific data type. int *pointer1 = &x; addr of x 0x2000 int x; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 1 0x9060 44 Pointer Operations Type Type*

object; aPtr; aPtr = &object assigns the address of object to aPtr. *aPtr allows access to the object through the pointer. If aPtr points to a structure then (*aPtr).member is equivalent to aPtr member copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 45 Pointers and Function Arguments x: 1 y:

2 swap copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE x: 2 y: 1 46 #include void fakeSwap(int a, int b) { int tmp; tmp = a;

a = b; b = tmp; } int main() { int x = 1, y = 2; fakeSwap(x, y); printf(%d %d\n, x, y); } Solution 1 #include Solution 1 void fakeSwap(int a, int b) { int tmp; tmp = a; a = b; b = tmp;

} int main() { int x = 1, y = 2; fakeSwap(x, y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void fakeSwap(int a, int b) {

int tmp; tmp = a; a = b; b = tmp; Solution 1 tmp: a: b: 0x2060 1 0x2038 2 0x2040 } int main() {

int x = 1, y = 2; fakeSwap(x, y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void fakeSwap(int a, int b) { int tmp; tmp = a; a = b;

b = tmp; Solution 1 tmp: a: b: 1 0x2060 1 0x2038 2 0x2040 } int main() { int x = 1, y = 2;

fakeSwap(x, y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void fakeSwap(int a, int b) { int tmp; tmp = a; a = b; b = tmp;

Solution 1 tmp: a: b: 1 0x2060 2 0x2038 2 0x2040 } int main() { int x = 1, y = 2; fakeSwap(x, y);

printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void fakeSwap(int a, int b) { int tmp; tmp = a; a = b; b = tmp;

Solution 1 tmp: a: b: 1 0x2060 2 0x2038 1 0x2040 } int main() { int x = 1, y = 2; fakeSwap(x, y); printf(%d %d\n, x, y);

} x: y: 1 0x2000 2 0x2010 #include Solution 1 void fakeSwap(int a, int b) { int tmp; tmp = a; a = b;

b = tmp; } int main() { int x = 1, y = 2; fakeSwap(x, y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void trueSwap(int* a, int* b)

{ int tmp; tmp = *a; *a = *b; *b = tmp; } int main() { int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } Solution 2 #include Solution 2 void trueSwap(int* a, int* b) { int tmp;

tmp = *a; *a = *b; *b = tmp; } int main() { int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include

void trueSwap(int* a, int* b) { int tmp; tmp = *a; *a = *b; *b = tmp; Solution 2 tmp: a: b: 0x2060 addr of x 0x2038 addr of y 0x2040

} int main() { int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void trueSwap(int* a, int* b) {

int tmp; tmp = *a; *a = *b; *b = tmp; Solution 2 tmp: a: b: 1 0x2060 addr of x 0x2038 addr of y 0x2040 }

int main() { int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } x: y: 1 0x2000 2 0x2010 #include void trueSwap(int* a, int* b) { int tmp;

tmp = *a; *a = *b; *b = tmp; Solution 2 tmp: a: b: 1 0x2060 addr of x 0x2038 addr of y 0x2040 } int main()

{ int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } x: y: 2 0x2000 2 0x2010 #include void trueSwap(int* a, int* b) { int tmp; tmp = *a;

*a = *b; *b = tmp; Solution 2 tmp: a: b: 1 0x2060 addr of x 0x2038 addr of y 0x2040 } int main() {

int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } x: y: 2 0x2000 1 0x2010 #include Solution 2 void trueSwap(int* a, int* b) {

int tmp; tmp = *a; *a = *b; *b = tmp; } int main() { int x = 1, y = 2; trueSwap(&x, &y); printf(%d %d\n, x, y); } x: y: 2 0x2000 1 0x2010

More on Pointers You can print the address stored in a pointer using the %p conversion specifier Example: printf(%p, numPtr); needs to know where to put the value - it needs the address of the variable as it takes pointers as parameters. scanf Example: int i; scanf(%d, &i); copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 61 struct DataBaseRec { /* Very Large Structure */

}; typedef struct DataBaseRec DataBase; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 62 DataBase readNewEntry(DataBase theDataBase) { /* Some code */ return theDataBase; } void printDataBase(DataBase theDataBase) { /* Some more code */ }

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 63 void readNewEntry(DataBase* dataBasePtr) { /* Some code */ } void printDataBase(const DataBase* dataBasePtr) { /* Some more code */ } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 64

void readNewEntry(DataBase* (DataBase* dataBasePtr) { /* Some code */ Address of Database } void printDataBase(const Database* DataBase* dataBasePtr) { /* Some more code */ } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 65

void readNewEntry(DataBase* dataBasePtr) { /* Some code */ } Database cannot change in this function. void const DataBase* dataBasePtr) printDataBase(const { /* Some more code */ } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 66 int readstudent(Student *student)

{ printf(Enter a name: \n); if (scanf(%s, student->name) == 1) { printf(Enter a mark: \n); if (scanf(%d, &(student->mark)) == 1) { return 1; } } Why do you need the brackets? return 0; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 67 Pointers and Functions To enable a function to access and change

an object. For large structures it is more efficient. Use const specifier whenever a constant is intended. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 68 Pointers and Arrays Type array[size]; Type* pPtr = array + i; Type* qPtr = array + j; The name array is equivalent to &array[0] pPtr++ increments pPtr to point to the next element of array. pPtr += n increments pPtr to point to n elements beyond where it currently points. pPtr-qPtr equals i-j. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

69 Pointers and Arrays (cont) A normal 1 dimensional array: Type array[size]; array[0] is equivalent to *array array[n] is equivalent to *(array + n) copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 70 Basic Pointer Arithmetic array: 0x2008 0x200C 0x2010

0x2014 0x2018 0x2008 0 1 pPtr: 0x2004 float 2 3 4 qPtr:

0x2008 0x2000 NULL array[5]; float* pPtr = array; float* qPtr = NULL; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 71 array: 0x2008 0x200C 0x2010

0x2014 0x2018 0x2008 0 1 pPtr: 0x2004 float 2 3 4 qPtr:

0x200C 0x2000 NULL array[5]; float* pPtr = array; float* qPtr = NULL; pPtr++; /* pPtr now holds the address: &array[1] */ copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 72 array: 0x2008 0x200C

0x2010 0x2014 0x2018 0x2008 0 1 pPtr: 0x2004 float 2 3 4 qPtr:

0x2018 0x2000 NULL array[5]; float* pPtr = array; float* qPtr = NULL; pPtr++; /* pPtr = &array[1] */ pPtr += 3; /* pPtr now hold the address: &array[4] */ copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 73 array: 0x2008

0x200C 0x2010 0x2014 0x2018 0x2008 0 1 pPtr: 0x2004 float 2 3 4

qPtr: 0x2018 0x2000 0x2010 array[5]; float* pPtr = array; float* qPtr = NULL; pPtr++; /* pPtr = &array[1] */ pPtr += 3; /* pPtr = &array[4] */ qPtr = array + 2; /*qPtr now holds the address &array[2]*/ copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 74 array:

0x2008 0x200C 0x2010 0x2014 0x2018 0x2008 0 1 2 pPtr: 0x2004 float

3 4 qPtr: 0x2018 0x2000 0x2010 array[5]; float* pPtr = array; float* qPtr = NULL; pPtr++; /* pPtr = &array[1] */ pPtr += 3; /* pPtr = &array[4] */ qPtr = array + 2; /* qPtr = &array[2] */ copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

printf(%d\n, pPtr-qPtr); 75 char* strcpy(char* s, char* t) { int i = 0; while (t[i] != 0) { s[i] = t[i]; i++; } return s; } char* strcpy(char* s, char* t) { char* p = s; while (*p != 0) { *p = *t; p++;

t++; } return s; } Revision Pointers Pointer Operations address operator (&), and dereferencing operator (*) Pointers and Structures. structure pointer operator (->) Pointers and Function Arguments. Look at swap example Pointer Arithmetic Pointers and Arrays copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 77

Next Lecture Stacks abstract data type main operations implementation copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 78 Basic Data Structures Stacks Queues Lists copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 79 Overview of Stacks

What is a Stack? Operations on a Stack push, pop initialize status: empty, full Implementation of a Stack. Example: Reversing a sequence. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 80 A Stack Top Items on the Stack copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 81

Push Top Top Before After copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 82 Pop This comes off the stack Top Top Before After

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 83 Operations Initialize the Stack. Pop an item off the top of the stack. Push an item onto the top of the stack. Is the Stack empty? Is the Stack full? Clear the Stack Determine Stack Size copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

84 Stack Properties Sequence of items, where insertions and deletions are done at the top. Main operations are pop and push. Last-In First Out (LIFO). Used when calling functions. Used when implementing recursion. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 85 Implementation : 2 Top index

1 array (upside-down) 0 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 86 Implementation : 2 Top int top; 1 float

entry[MAXSTACK]; 0 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 87 #ifndef STACK.H #define STACK.H #include #define MAXSTACK 20 struct StackRec { int top; float entry[MAXSTACK]; }; typedef struct StackRec Stack; void intializeStack(Stack* stackPtr); bool stackEmpty(const Stack* stackPtr); bool stackFull(const Stack* stackPtr); void push(Stack* stackPtr, float item);

float pop(Stack* stackPtr); #endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 88 Stack: #define MAXSTACK top: 20 struct StackRec { int top; float entry[MAXSTACK]; }; entry:

. . . typedef struct StackRec Stack; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89 #include #include #include stack.h void initializeStack(Stack* stackPtr) { stackPtr -> top = -1; } stackPtr: addr of Stack Stack:

top: -1 entry: . . . copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 90 bool stackEmpty(const Stack* stackPtr) { if (stackPtr-> top < 0) { return true; } else { return false; }

} copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 91 bool stackFull(const Stack* stackPtr) { if (stackPtr -> top >= MAXSTACK-1) { return true; } else { return false; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 92

void push(Stack* stackPtr, float item) { if (stackFull(stackPtr)) { fprintf(stderr, Stack is full\n); exit(1); } else { stackPtr-> top++; stackPtr-> entry[stackPtr-> top] = item; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 93 float pop(Stack* stackPtr) { float item; if (stackEmpty(stackPtr))

{ fprintf(stderr, Stack is empty\n); exit(1); } else { item = stackPtr-> entry[stackPtr-> top]; stackPtr-> top--; } return item; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 94 #include #include stack.h int main() { Stack theStack; float next;

initializeStack(&theStack); printf(Enter number sequence: ); while (scanf(%f, &next) != EOF) { if (!stackFull(&theStack)) { push(&theStack, next); } } while (!stackEmpty(&theStack)) { next = pop(&theStack); printf(%f, next); } copy right (version1.0) SUNITHA printf(\n); C.N,CS&E dept,SJCE 95 Revision Stack Operations on a Stack

push, pop initialize status: empty, full others: clear, size Implementation. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 96 Next Lecture Queue Main Operations Implementation copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 97

Basic Data Structures Stacks Queues Lists copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 98 Overview What is a Queue? Queue Operations. Applications. Linear Implementation. Circular Implementation.

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 99 Before Front After Front Insert Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Rear100 Before

Delete Front Rear After Front Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE This comes off the queue 101 Operations

Initialize the queue. Append an item to the rear of the queue. Serve an item from the front of the queue. Is the queue empty? Is the queue full? What size is the queue? copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 102 Applications In operating systems, e.g. printer queues, process queues, etc. Simulation programs. Algorithms. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

103 Linear Implementation 0 Front 1 2 3 4 5 6 7 Rear

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 104 Insert 0 1 2 3 4 Front 5 6

7 Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 105 Insert 0 1 2 3 4 Front 5

6 7 Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 106 Delete 0 1 2 3 4

5 Front 6 7 Rear This comes off the queue copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 107 Delete 0 1 2

3 4 5 6 7 Rear Front This comes off the queue copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 108 Insert 0

1 2 3 4 Front copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 5 6 7 Rear 109

Insert 0 1 2 3 4 Front 5 6 7 Rear NO SPACE

HERE copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 110 Insert 0 1 SPACE HERE 2 3 4 Front copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 5 6 7 Rear 111 Circular Implementation 7 0 6 1 5

2 4 3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 112 Circular Implementation 0 1 2 3 4 Front

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 5 6 7 Rear 113 Insert 0 Rear 1 2

3 4 5 6 7 Front copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 114 #ifndef QUEUE.H #define QUEUE.H #include #define MAXQUEUE 20 struct QueueRec {

int count; int front; int rear; float entry[MAXQUEUE]; }; typedef struct QueueRec Queue; void intializeQueue(Queue* queuePtr); bool queueEmpty(const Queue* queuePtr); bool queueFull(const Queue* queuePtr); void append(Queue* queuePtr, float item); float serve(Queue* queuePtr); #endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 115 Queue: #define MAXQUEUE

20 struct QueueRec { int count; int front; int rear; float entry[MAXQUEUE]; }; typedef struct QueueRec Queue; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE count: front: rear: entry:

. . . 116 #include #include #include queue.h void initializeQueue(Queue* queuePtr) { queuePtr -> count = 0; queuePtr -> front = 0; queuePtr -> rear = MAXQUEUE-1; } queuePtr: addr of Queue Queue: count:

0 front: 0 rear: 19 entry: . . . copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 117 bool queueEmpty(const Queue* queuePtr) { if (queuePtr->count <= 0)

{ return true; } else { return false; } } bool queueFull(Queue* queuePtr) { if (queuePtr->count >= MAXQUEUE) { return true; } else { return false; } } void

append(Queue* queuePtr, float item) { if (queueFull(queuePtr)) { fprintf(stderr, Queue is full\n); exit(1); } else { queuePtr->rear++; if (queuePtr->rear == MAXQUEUE) { queuePtr->rear = 0; } queuePtr->entry[queuePtr->rear] = item; queuePtr->count++; } } float serve(Queue* queuePtr) { float item; if (queueEmpty(queuePtr))

{ fprintf(stderr, Queue is empty\n); exit(1); } else { item = queuePtr->entry[queuePtr->front]; queuePtr->front++; if (queuePtr->front == MAXQUEUE) { queuePtr->front = 0; } queuePtr->count--; } return item; } Revision Queue Main Operations Implementation. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

122 Basic Data Types Stack Last-In, First-Out (LIFO) initialize, push, pop, status Queue First-In, First-Out (FIFO) initialize, Insert, delete, status List copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 123 Overview

Lists. Operations. Abstract Data Types (ADT). Programming Styles. Implementations of Lists. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 124 Lists APE DEER EMU FOX

SEAL 0 1 2 3 4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 125 Insertion EMU Inserted at position 2 Before: APE

DEER FOX SEAL 0 1 2 3 APE DEER EMU FOX SEAL

0 1 2 3 4 After: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 126 Deletion Delete item at position 3 Before: APE

DEER EMU FOX SEAL 0 1 2 3 4 APE DEER

EMU SEAL 0 1 2 3 After: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 127 List Operations

Initialize the list. Determine whether the list is empty. Determine whether the list is full. Find the size of the list. Insert an item anywhere in the list. Delete an item anywhere in a list. Go to a particular position in a list. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 128 A List ADT A sequence of elements together with these operations:

Initialize the list. Determine whether the list is empty. Determine whether the list is full. Find the size of the list. Insert an item anywhere in the list. Delete an item anywhere in a list. Go to a particular position in a list. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 129 Abstract Data Type (ADT) A Data Structure together with operations defined on it. Useful to consider what operations are required before starting implementation. Led to the development of object oriented

programming. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 130 A Stack ADT A sequence of elements together with these operations: Initialize the stack. Determine whether the stack is empty. Determine whether the stack is full. Push an item onto the top of the stack. Pop an item off the top of the stack. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

131 A Queue ADT A sequence of elements together with these operations: Initialize the queue. Determine whether the queue is empty. Determine whether the queue is full. Find the size of the queue. Append an item to the rear of the queue. Serve an item at the front of the queue. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 132

Comparison Stacks Insert at the top of the stack (push) Delete at the top of the stack (pop) Queues Insert at the rear of the queue (append) Delete at the front of the queue (serve) Lists Insert at any position in the list. Delete at any position in the list. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 133 A Rational Number ADT Two integers together with these operations:

Initialize the rational number. Get the numerator. Get the denominator. Simplify a rational number. Add two rational numbers. Determine whether two rational numbers are equal. etc. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 134 A String ADT A array of characters together with these operations:

Initialize the string. Copy a string. Read in a line of input. Concatenate two strings. Compare two strings. Find a length of a string. etc. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 135 Simple List Implementation EMU APE 0

DEER 1 FOX 2 SEAL 3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 4 5 136 Simple List Implementation EMU APE

0 DEER 1 2 FOX 3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE SEAL 4 5 137 Simple List Implementation APE

0 DEER 1 EMU 2 FOX 3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE SEAL 4 5 138 Linked List Implementation: Using Array Index

start data 0 1 2 3 DEER FOX APE SEAL 1 3

0 -1 link to next item 4 5 marks last item139 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Linked List Implementation: Using Array Index insert: EMU start 0

1 2 3 4 DEER FOX APE SEAL EMU 1 3 0

-1 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 5 140 Linked List Implementation: Using Array Index insert: EMU start 0 1 2

3 4 DEER FOX APE SEAL EMU 4 3 0 -1

1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 5 141 Linked List Implementation: Using Pointers start 0x2000 0x2008 0x2010 0x2018 0x2020 DEER

FOX APE SEAL EMU 0x2020 0x2018 0x2000 NULL 0x2008 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x2018

142 Linked List Implementation: Using Pointers special pointer constant start 0x2000 0x2008 0x2010 0x2018 0x2020 DEER FOX

APE SEAL EMU 0x2020 0x2018 0x2000 NULL 0x2008 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x2018 143

Revision List initialize, insert, delete, position, status implementations Difference between Stacks, Queues, and Lists. ADT. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 144 Overview Linked Stack. Push Pop Linked Queue. Insert Delete

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 145 Linked Stack Top of the Stack NULL pointer copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 146 #ifndef LINKEDSTACKH #define LINKEDSTACKH #include #include node.h struct LinkedStackRec { Node* topPtr; }; typedef struct LinkedStackRec Stack;

void intializeStack(Stack* stackPtr); bool stackEmpty(const Stack* stackPtr); bool stackFull(const Stack* stackPtr); void push(Stack* stackPtr, float item); float pop(Stack* stackPtr); #endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 147 Initialize Stack void initializeStack(Stack* stackPtr) { stackPtr->topPtr = NULL; } Push Top Top copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 149 Push create a new node for the item link the new node to the current top node make the new node the new top copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 150 Push void push(Stack* stackPtr, float item) { Node* newNodePtr = makeNode(item); newNodePtr->nextPtr = stackPtr->topPtr; stackPtr->topPtr = newNodePtr; }

Pop Top Top copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 152 Pop check if the stack is empty remember the item in the top node remember address of current top node make the next node the new top free the old top node return the item

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 153 Pop float pop(Stack* stackPtr) { float item; Node* oldNodePtr = stackPtr->topPtr; if (stackEmpty(stackPtr)) { fprintf(stderr, Stack is empty\n); exit(1); } else { item = oldNodePtr->value; stackPtr->topPtr = oldNodePtr->nextPtr; free(oldNodePtr); } return item; } Linked Queue

Front Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 155 #ifndef LINKEDQUEUEH #define LINKEDQUEUEH #include #include node.h struct LinkedQueueRec { int count; Node* frontPtr; Node* rearPtr; }; typedef struct LinkedQueueRec Queue; void intializeQueue(Queue* queuePtr);

bool queueEmpty(const Queue* queuePtr); bool queueFull(const Queue* queuePtr); void append(Queue* queuePtr, float item); float serve(Queue* queuePtr); #endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 156 Initialize Queue void initializeQueue(Queue* queuePtr) { queuePtr->frontPtr = NULL; queuePtr->rearPtr = NULL; queuePtr->count = 0; } Insert Front

Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 158 Insert Front Rear Front Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 159 Insert create a new node for the item

if the queue is empty: the new node becomes both front and rear of the queue otherwise: make a link from the current rear to the new node the new node becomes the new rear increment the count copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 160 void append(Queue* queuePtr, float item) { Node* newNodePtr = makeNode(item); if (queueEmpty(queuePtr)) { queuePtr->frontPtr = newNodePtr; queuePtr->rearPtr = newNodePtr; queuePtr->count = 1; }

else { queuePtr->rearPtr->nextPtr = newNodePtr; queuePtr->rearPtr = newNodePtr; queuePtr->count++; } } Delete Front Rear copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 162 Delete Front Rear

Front copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Rear 163 Delete check that the queue is not empty remember the item in the front node remember the address of the front node make the next node the new front free the old front node

decrement count if queue is now empty, set rear to NULL return the item copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 164 float serve(Queue* queuePtr) { float item; Node* oldNodePtr = queuePtr->frontPtr; if (queueEmpty(queuePtr)) { fprintf(stderr, Queue is empty\n); exit(1); } else { item = oldNodePtr->value; queuePtr->frontPtr = oldNodePtr->nextPtr; queuePtr->count--; free(oldNodePtr); if (queuePtr->count == 0) { queuePtr->rearPtr = NULL;

} } return item; } #include #include linkedqueue.h main() { Queue float theQueue; item; initializeQueue(&theQueue); while (scanf(%f, &item) != EOF) { append(&theQueue, item); } while (!queueEmpty(&theQueue)) { item = serve(&theQueue);

printf(%f\n, item); } } Revision Linked Stack. Initialize, Pop, Push. Linked Queue. Initialize, Insert,Delete copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 167 Overview What is Dynamic Memory ?

How to find the size of objects. Allocating memory. Deallocating memory. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 168 Virtual Memory Text Segment program instructions Data Segment static and dynamic data free memory Stack segment local variables, parameters

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 169 Virtual Memory Text Segment Static data Heap global variables, etc. dynamic data Stack segment copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 170 Virtual Memory Text Segment

Static data Heap memory is allocated and deallocated as needed Stack segment copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 171 What is Dynamic Memory? Memory which is allocated and deallocated during the execution of the program. Types: data in run-time stack dynamic data in the heap copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 172

Example: Run-Time Stack Memory is allocated when a program calls a function. parameters local variables where to go upon return Memory is deallocated when a program returns from a function. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 173 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:

11: 12: 13: 14: 15: 16: 17: 18: #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; stack

b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 174 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15:

16: 17: 18: #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; stack b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

a 3.15 b 175 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15:

16: 17: 18: #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; stack b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

x 3.15 a 3.15 b 176 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

12: 13: 14: 15: 16: 17: 18: #include float square(float x) { float result; result = x * x; return result; stack } line 16 main() {

float a = 3.15; float b; b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE x 3.15 a 3.15 b 177 01: 02: 03: 04:

05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: #include float square(float x) { float result; result = x * x; return result; stack

result } line 16 main() { float a = 3.15; float b; b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE x 3.15 a 3.15

b 178 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18:

#include float square(float x) { float result; result = x * x; return result; stack result } 9.9225 line 16 main() { float a = 3.15; float b; b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE x 3.15 a 3.15 b 179 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:

11: 12: 13: 14: 15: 16: 17: 18: #include float square(float x) { float result; result = x * x; return result; stack result } 9.9225 line 16

main() { float a = 3.15; float b; b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE x 3.15 a 3.15 b 180 01:

02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: #include float square(float x) { float result; result = x * x;

return result; } main() { float a = 3.15; float b; stack b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE a 3.15 b 9.9225 181

01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: #include float square(float x) {

float result; result = x * x; return result; } main() { float a = 3.15; float b; stack b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE a 3.15 b

9.9225 182 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: #include

float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; stack b = square(a); printf(%f\n, b); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 183 #include #include

int factorial (int x) { if (x == 0) { return 1; } return x * factorial (x 1); } void main() { int n; printf(Enter a number: \n); scanf(%d, &n); printf(Factorial: %d\n, factorial(n); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 184 How much memory to allocate? The sizeof operator returns the size of an

object, or type, in bytes. Usage: sizeof(Type) sizeof Object copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 185 Example 1: int char float double n; str[25]; x; numbers[36]; printf(%d\n, sizeof(int)); printf(%d\n, sizeof n); n

n n n = = = = sizeof str; sizeof x; sizeof(double); sizeof numbers; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 186 Notes on sizeof Do not assume the size of an object, or type; use sizeof instead. Example:

int n; In DOS: 2 bytes (16 bits) In GCC/Linux: 4 bytes (32 bits) In MIPS: 4 bytes (32 bits) copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 187 Example 2: #include #define MAXNAME #define MAXCLASS 80 100 struct StudentRec { char name[MAXNAME]; float

mark; }; typedef struct StudentRec Student; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 188 Example 2 (cont.): int main() { int Student n; class[MAXCLASS]; n = sizeof(int); printf(Size of int = %d\n, n); n = sizeof(Student); printf(Size of Student = %d\n, n); n = sizeof class;

printf(Size of array class = %d\n, n); return 0; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 189 Notes on sizeof (cont.) The size of a structure is not necessarily the sum of the sizes of its members. Example: struct cardRec { char suit; int number; }; alignment and padding typedef struct cardRec Card;

Card hand[5]; printf(%d\n, sizeof(Card)); printf(%d\n, sizeof hand); 5*sizeof(Card) copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 190 Dynamic Memory: Heap Memory can be allocated for new objects. Steps: determine how many bytes are needed allocate enough bytes in the heap take note of where it is (memory address) copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 191 Example 1: heap #include

main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } stack aPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE NULL 192 Example 1: heap #include 0x3a04 main()

{ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } stack aPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x3a04 NULL 193 Example 1: type cast #include heap

0x3a04 main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } stack aPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x3a04 NULL 194 Example 1: heap #include

0x3a04 5 main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } stack aPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x3a04 195 Example 1: heap #include

main() { int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } stack aPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x3a04 196 Example 1: heap #include main() { int* aPtr = NULL;

deallocates memory aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; free(aPtr); } stack aPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x3a04 197 #include Example 2: main() { int* aPtr;

int* bPtr; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5; bPtr = (int*)malloc(sizeof(int)); *bPtr = 8; free(aPtr); aPtr = bPtr; bPtr = (int*)malloc(sizeof(int)); *bPtr = 6; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 198 Allocating Memory Need to include stdlib.h malloc(n) returns a pointer to n bytes of memory. Always check if malloc has returned the NULL pointer. Apply a type cast to the pointer returned by

malloc. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 199 Deallocating Memory free(pointer) deallocates the memory pointed to by a pointer. It does nothing if pointer == NULL. pointer must point to memory previously allocated by malloc. Should free memory no longer being used. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 200 Example 3: main() { Student*

studentPtr = NULL; studentPtr = (Student*)malloc(sizeof(Student)); if (studentPtr == NULL) { fprintf(stderr, Out of memory\n); exit(1); } *studentPtr = readStudent(); printStudent(*studentPtr); free(studentPtr); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 201 main() { Student* class = NULL; int n, i, best = 0;

Example 4: printf(Enter number of Students: ); scanf(%d, &n); class = (Student*)malloc(n * sizeof(Student)); if (class != NULL) { for (i = 0; i < n; i++) { class[i] = readStudent(); if (class[best].mark < class[i].mark) { best = i; } } printf(Best student: ); printStudent(class[best]); } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 202 Common Errors

Assuming that the size of a structure is the sum of the sizes of its members. Referring to memory already freed. Not freeing memory which is no longer required. Freeing memory not allocated by malloc. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 203 #include #include Example 5: float** makeMatrix(int n, int m){ float* memoryPtr; float** matrixPtr; int i; memoryPtr = (float*)malloc(n*m*sizeof(float)); matrixPtr = (float**)malloc(n*sizeof(float*));

if (memoryPtr == NULL || matrixPtr == NULL) { fprintf(stderr, Not enough memory\n); exit(1); } for (i = 0; i < n; i++, memoryPtr += m){ matrixPtr[i] = memoryPtr; } return matrixPtr; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 204 Revision sizeof malloc

free Common errors. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 205 Overview of Topic Review List Implementations. Nodes. Linked Stacks. Linked Queues Linked Lists. Other List Operations copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE Todays Lecture 206 Lists 1 3 6 10 15 0 1

2 3 4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 207 A List ADT A sequence of elements together with these operations: Initialize the list. Determine whether the list is empty. Determine whether the list is full. Find the size of the list. Insert an item anywhere in the list. Delete an item anywhere in a list. Go to a particular position in a list. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

208 Insertion 6 Before: Inserted at position 2 1 3 10 15 0 1 2

3 1 3 6 10 15 0 1 2 3 4

After: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 209 A List ADT A sequence of elements together with these operations: Initialize the list. Determine whether the list is empty. Find the size of the list. Insert an item anywhere in the list. Delete an item anywhere in a list. Go to a particular position in a list. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

List needs to be able to expand 210 Simple List Implementation 6 1 3 10 15 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 21 211

Expansion and Insertion 1 3 10 15 21 Copy old array, leave space for the new value 1 3 6 10 15

21 6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 212 Disadvantages Lots of memory needs to be allocated. Lots of copying needs to be done. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 213 Linked List Implementation: Using Pointers insert: 6 start

0x2000 0x2008 0x2010 0x2018 0x2020 3 15 1 21 10 0x2020 0x2018

0x2000 NULL 0x2008 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 214 Method 1 start 0x30F0 0x2000 0x2008 0x2010 0x2018

0x2020 3 15 1 21 10 0x2020 0x2018 0x2000 NULL 0x2008

newStart 0x30F0 insert: 6 Copy old array, leave space for the new value 0x30F8 0x3100 0x3108 0x3110 1 3 6 10 15 0x30F8 0x3100 0x3108 0x3110 0x3118 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

0x3118 21 NULL 215 Method 2 start 0x2000 0x2008 0x2010 0x2018 0x2020 3

15 1 21 10 0x2020 0x2018 0x2000 NULL 0x2008 insert: 6 0x30F0 newItem

6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 216 Method 2 start 0x2000 0x2008 0x2010 0x2018 0x2020 3

15 1 21 10 0x30F0 0x2018 0x2000 NULL 0x2008 insert: 6 0x30F0

newItem 6 0x2020 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 217 Advantages Only a little amount of memory needs to be allocated. Only a little amount of copying needs to be done. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 218 Node: struct NodeRec {

float value; struct NodeRec* nextPtr; }; value: nextPtr: typedef struct NodeRec Node; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 219 #ifndef NODE.H #define NODE.H struct NodeRec { float value; struct NodeRec* nextPtr; }; typedef struct NodeRec Node; Node* makeNode(float item);

#endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 220 Make Node To make a new node for an item take enough bytes from the heap remember its address in memory put the item in that location set next link to NULL return the nodes address copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

221 Node* makeNode(float item) { Node* newNodePtr = (Node*)malloc(sizeof(Node)); if (newNodePtr == NULL) { fprintf(stderr, Out of memory); exit(1); } else { newNodePtr->value = item; newNodePtr->nextPtr = NULL; } return newNodePtr; } #include #include #include node.h int main() {

float item; Node* firstNodePtr = NULL; Node* lastNodePtr = NULL; while (scanf(%f, &item) != EOF){ if (firstNodePtr == NULL){ firstNodePtr = makeNode(item); lastNodePtr = firstNodePtr; } else { lastNodePtr->nextPtr = makeNode(item); lastNodePtr = lastNodePtr->nextPtr; } } } firstNodePtr: lastNodePtr: 0x30F0 0x30F0 0x2124

0x2A40 0x2124 value: 1 nextPtr: 0x2A40 value: 6 nextPtr: NULL value:

3 nextPtr: 0x2124 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE item: 6 224 Linked Structure 0x30F0 1 0x2A40 0x2124

6 NULL 0x2A40 3 0x2124 firstNodePtr: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x30F0 225 Linked Structure 0x30F0 1

firstNodePtr: 0x2A40 0x2A40 3 0x2124 0x30F0 0x2124 6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE NULL 226 Linked Structure firstNodePtr:

1 3 6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 227 Linked Structure firstNodePtr: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 228 Revision Node How to make a new Node Linked Structure copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 229 Overview Operations for Lists. Implementation of Linked Lists. Double Linked Lists. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 230 List Operations Go to a position in the list.

Insert an item at a position in the list. Delete an item from a position in the list. Retrieve an item from a position. Replace an item at a position. Traverse a list. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 231 Comparsion Linked Storage Unknown list size. Flexibility is needed. Contiguous Storage Known list size. Few insertions and deletions are made within the list. Random access copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 232

Linked List Head 0 1 2 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 3 233 #ifndef LINKEDLISTH #define LINKEDLISTH #include #include node.h struct LinkedListRec {

int count; Node* headPtr; }; typedef struct LinkedListRec List; void intializeList(List* listPtr); bool listEmpty(const List* listPtr); Node* setPosition(const List* listPtr, int position); void insertItem(List* listPtr, float item, int position); float deleteNode(List* listPtr, int position); #endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 234 Initialize List listPtr addr of list count

headPtr 0 NULL void initializeList(List* listPtr) { listPtr->headPtr = NULL; listPtr->count = 0; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 235 Set Position check if position is within range

start with address of head node set count to 0 while count is less than position follow link to next node increment count return address of current node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 236 Set Position Head 0 2 1 2 position copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 237 Node* setPosition(const List* listPtr, int position) { int i; Node* nodePtr = listPtr->headPtr; if (position < 0 || position >= listPtr->count) { fprintf(stderr, Invalid position\n); exit(1); } else { for (i = 0; i < position; i++) { nodePtr = nodePtr->nextPtr; } } return nodePtr; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

238 Set Position Head 0x4000 2 position 0 i 0x4000 0x2030 0x30a8 NodePtr copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 239 Set Position Head 0x4000 2 position 0 i 0x4000 0x2030 0x30a8 NodePtr

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 240 Set Position Head 0x4000 2 position 1 i 0x2030 0x2030 0x30a8

NodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 241 Set Position Head 0x4000 2 position 2 i 0x30a8 0x2030

0x30a8 NodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 242 Insert Head 0 1 2 If we insert it at position 0. 0 1

2 Head copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 243 Insert Head 0 1 2 If we insert it at position 0. 0 1

2 3 Head copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 244 Instead, suppose we insert it at position 1. Head 0 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2 245

Instead, suppose we insert it at position 1. Head 0 2 3 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 246 void insertItem(List* listPtr, float item, int position) { Node* newNodePtr = makeNode(item); Node* nodePtr = NULL; if (position == 0) { newNodePtr->nextPtr = listPtr->headPtr;

listPtr->headPtr = newNodePtr; } else { nodePtr = setPosition(listPtr, position-1); newNodePtr->nextPtr = nodePtr->nextPtr; nodePtr->nextPtr = newNodePtr; } listPtr->count++; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 247 Inserting New List Head 0 0x30a8 NULL

0x30a8 position newNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 248 Inserting New List 0x30a8 Head 0 0x30a8 position

newNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 249 Inserting Start of List Head 0x2008 0x30a8 0x2000 newNodePtr 0x2000 position 0 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

250 Inserting Start of List Head 0x2008 0x30a8 0x2000 newNodePtr 0x2000 position 0 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 251 Inserting Start of List

Head 0x2008 0x30a8 0x2000 newNodePtr 0x2000 position 0 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 252 Inserting Inside the List Head 0x3080 NodePtr

0x3050 0x3080 0x2000 newNodePtr 0x2000 position 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 253 Inserting Inside the List Head 0x3080 NodePtr

0x3050 0x3080 0x2000 newNodePtr 0x2000 position 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 254 Inserting Inside the List Head 0x3080 NodePtr

0x3050 0x3080 0x2000 newNodePtr 0x2000 position 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 255 Delete Head 0

1 2 3 If we delete the Node at position 0. 0 1 2 Head copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 256 If we delete the Node at position 2. Head

0 1 2 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 3 257 If we delete the Node at position 2. Head 0 1 2

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2 258 void deleteNode(List* listPtr, int position) { Node* oldNodePtr = NULL; Node* nodePtr = NULL; if (listPtr->count > 0 && position < listPtr->count) { if (position == 0) { oldNodePtr = listPtr->headPtr; listPtr->headPtr = oldNodePtr->nextPtr; } else { nodePtr = setPosition(listPtr, position - 1); oldNodePtr = nodePtr->nextPtr; nodePtr->nextPtr = oldNodePtr->nextPtr; } listPtr->count--;

free(oldNodePtr); } else { fprintf(stderr, List is empty or invalid position.\ n); exit(1); copy right (version1.0) SUNITHA 259 } C.N,CS&E dept,SJCE Deleting 1 Node st Head 0x4000 0 position 0x4000

NodePtr 0x2030 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x30a8 260 Deleting 1 Node st 0x4000 0 position 0x4000 NodePtr

0x2030 0x30a8 Head copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 261 Deleting 1 Node st 0x2030 0 position 0x4000

NodePtr 0x30a8 Head copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 262 Deleting Middle Node Head 0x4000 1 position 0x2030 NodePtr

0x2030 OldNodePtr 0x2030 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x30a8 263 Deleting Middle Node Head 0x4000 1 position 0x2030

NodePtr 0x2030 OldNodePtr 0x2030 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x30a8 264 Deleting Middle Node Head 0x4000 1 position

0x2030 NodePtr 0x2030 OldNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x30a8 265 Double Linked List Operations

Go to a position in the list. Insert an item in a position in the list. Delete an item from a position in the list. Retrieve an item from a position. Replace an item at a position. Traverse a list, in both directions. directions copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 266 Double Linked List 0 1 2 3 4

Current copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 267 struct DoubleLinkNodeRec { float struct DoubleLinkNodeRec* struct DoubleLinkNodeRec* }; value; nextPtr; previousPtr; typedef struct DoubleLinkNodeRec Node; struct DoubleLinkListRec { int count; Node*

currentPtr; int position; }; typedef struct DoubleLinkListRec DoubleLinkList; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 268 Insert at end 0x4000 0x3080 NULL 0x3080 0x2030 0x4000 0x2030

0x2000 NULL NULL 0x3080 NULL 0x2030 currentPtr prevPtr newPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x2000

269 Insert at end 0x4000 0x3080 NULL 0x3080 0x2030 0x4000 0x2030 0x2000 0x2000 NULL 0x3080

NULL 0x2030 currentPtr prevPtr newPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x2000 270 Insert at end 0x4000 0x3080 NULL

0x3080 0x2030 0x4000 0x2030 0x2000 0x2000 NULL 0x3080 0x2030 0x2030 currentPtr prevPtr

newPtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 0x2000 271 Insert inside the list 0x4000 0x3080 NULL 0x3080 0x2030 0x2030 NULL

0x4000 0x3080 0x2000 0x3080 currentPtr 0x2000 prevPtr NULL NULL copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE newPtr 272 Insert inside the list

0x4000 0x3080 NULL 0x3080 0x2030 0x2030 NULL 0x4000 0x3080 0x2000 0x3080 currentPtr 0x2000

prevPtr 2030 NULL copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE newPtr 273 Insert inside the list 0x4000 0x3080 NULL 0x3080 0x2030 0x2030

NULL 0x4000 0x3080 0x2000 0x3080 currentPtr 0x2000 prevPtr 2030 3080 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE newPtr

274 Insert inside the list 0x4000 0x3080 NULL 0x3080 0x2030 0x2030 NULL 0x4000 0x2000 0x2000 0x3080

currentPtr 0x2000 prevPtr 2030 3080 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE newPtr 275 Insert inside the list 0x4000 0x3080 NULL 0x3080

0x2030 0x2000 NULL 0x4000 0x2000 0x2000 0x3080 currentPtr 0x2000 prevPtr 2030 3080 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

newPtr 276 Delete from end 0x4000 0x3080 NULL currentPtr 0x3080 0x2030 0x4000 0x2030 NULL 0x3080

oldPtr 0x2030 prevPtr 0x3080 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 277 Delete from end 0x4000 0x3080 0x2030 0x3080 NULL NULL

0x4000 0x3080 NULL currentPtr oldPtr 0x2030 prevPtr 0x3080 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 278 Delete from end 0x4000 0x3080

0x3080 NULL NULL currentPtr 0x4000 oldPtr 0x2030 prevPtr 0x3080 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 279 Delete from inside list 0x4000

0x3080 NULL currentPtr 0x3080 0x2030 0x4000 0x2030 NULL 0x3080 oldPtr 0x3080 prevPtr 0x4000 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

280 Delete from inside list 0x4000 0x2030 NULL currentPtr 0x3080 0x2030 0x4000 0x2030 NULL 0x3080 oldPtr 0x3080

prevPtr 0x4000 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 281 Delete from inside list 0x4000 0x2030 NULL currentPtr 0x3080 0x2030 0x4000 0x2030 NULL

0x4000 oldPtr 0x3080 prevPtr 0x4000 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 282 Delete from inside list 0x4000 0x2030 0x2030 NULL NULL

currentPtr Head 0x4000 oldPtr 0x3080 prevPtr 0x4000 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 283 Revision Linked List. Benefits of different implementations. Double Linked List. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

284 Overview Selection Sort Insertion Sort Linear Search. Binary Search. Growth Rates. Implementation. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 285 Selection Sort First find the largest element in the array

and exchange it with the element in the last position, then find the second largest element in array and exchange it with the element in the second last position, and continue in this way until the entire array is sorted. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 286 Selection Sort 1 5 0 2 6 3

4 1 5 0 2 4 3 6 1 3 0

2 4 5 6 1 2 0 3 4 5 6

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 287 Insertion Sort The items of the array are considered one at a time, and each new item is inserted into the appropriate position relative to the previously sorted items. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 288 Insertion Sort 1 5 0

2 6 3 4 1 0 5 2 6 3 4 0

1 5 2 6 3 4 0 1 2 5 6

3 4 0 1 2 5 3 6 4 0 1 2

3 5 6 4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 289 Linear Search current -7 9 -5

2 8 3 -4 0 1 2 3 4 5 6

Target is -5 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 290 Linear Search current -7 9 -5 2 8 3 -4

0 1 2 3 4 5 6 Target is -5 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 291 Linear Search

current -7 9 -5 2 8 3 -4 0 1 2 3

4 5 6 Target is -5 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 292 Linear Search current -7 9 -5

2 8 3 -4 0 1 2 3 4 5 6 Numbers can be in any order.

Works for Linked Lists. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 293 Binary Search target Lower Part mid copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 294 Binary Search target Upper Part mid

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 295 Binary Search target Upper Part mid Need List to be sorted. To be able to do random accesses. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 296 Binary Search target -1

2 3 5 8 10 15 0 1 2 3 4

5 6 low mid copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE high 297 Binary Search target -1 2 3

5 8 10 15 0 1 2 3 4 5 6 low

mid high copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 298 Binary Search target -1 2 3 5 8 10

15 0 1 2 3 4 5 6 high low mid copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

299 Other Uses of Binary Search To find where a function is zero. Compute functions. Tree data structures. Data processing. Debugging code. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 300 Recall: Growth Rates / Complexity

Constant Logarithmic Linear n log(n) Quadratic Cubic Exponential

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE O(1) O(log(n)) O(n) O(n log(n)) O(n2) O(n3) O(2n) 301 Selection Sort First find the largest element in the array and exchange it with the element in the last position, then find the second largest element in array and exchange it with the element in the second last position, and continue in this way until the entire array is sorted. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

302 Find where the Maximum is. /* * Find the position of the maximum in * list[0],,list[k] */ maxPosition = 0; for (j = 1; j <= k; j++) { if (array[j] > array[maxPosition]) { maxPosition = j; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 303 void selectionSort(float array[], int size) { int j, k;

int maxPosition; float tmp; for (k = size-1; k > 0; k--) { maxPosition = 0; for (j = 1; j <= k; j++) { if (array[j] > array[maxPosition]) { maxPosition = j; } } tmp = array[k]; array[k] = array[maxPosition]; array[maxPosition] = tmp; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 304 Insertion Sort The items of the array are considered one

at a time, and each new item is inserted into the appropriate position relative to the previously sorted items. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 305 void insertionSort(float array[], int size) { int j, k; float current; for (k = 1; k < size; k++) { current = array[k]; j = k; while (j > 0 && current < array[j-1]) { array[j] = array[j-1]; j--; } array[j] = current; }

} copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 306 Linear Search current -7 9 -5 2 8 3 -4

0 1 2 3 4 5 6 Numbers can be in any order. Works for Linked Lists. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 307 Linear Search

int linearSearch(float array[], int size, int target) { int i; for (i = 0; i < size; i++) { if (array[i] == target) { return i; } } return -1; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 308 Binary Search mid Need List to be sorted.

To be able to do random accesses. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 309 Case 1: target < list[mid] target list: lower New upper mid copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE upper

310 Case 2: list[mid] < target target list: lower mid New lower copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE upper 311 int binarySearch(float array[], int size, int target) {

int lower = 0, upper = size - 1, mid; while (lower <= upper) { mid = (upper + lower)/2; if (array[mid] > target) { upper = mid - 1; } else if (array[mid] < target) { lower = mid + 1; } The section where else the target could be found { halves in size each time return mid; } } return -1; } copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 312 Comparison Array Linked List Selection Sort Insertion Sort Linear Search Binary Search copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 313 Revision

Selection Sort Insertion Sort Linear Search Binary Search copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 314 Overview Unary Recursion Binary Recursion Examples

Features Stacks Disadvantages Advantages copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 315 What is Recursion - Recall A procedure defined in terms of itself Components: Base case Recursive definition Convergence to base case copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 316 double power(double x, int n) {

int i double tmp = 1; if (n > 0) { for (i = 0; i < n; i++) { tmp *= x; } } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 317 double power(double x, int n) { double tmp = 1; if (n > 0) { tmp = power(x, n/2);

if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; } } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 318 Unary Recursion Functions calls itself once (at most) Usual format: function RecursiveFunction ( ) { if ( base case ) then return base value

else return RecursiveFunction ( ) } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 319 Unary Recursion /* Computes the factorial */ function Factorial ( n ) { if ( n is less than or equal to 1) then return 1 else return n Factorial ( n - 1 ) } int factorial ( int n ) { if ( n <= 1 )

{ return 1; } else { return n*factorial(n-1); } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 320 Binary Recursion Defined in terms of two or more calls to itself. For example Fibonacci A series of numbers which begins with 0 and 1 every subsequent number is the sum of the previous two numbers

0, 1, 1, 2, 3, 5, 8, 13, 21,... copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 321 Binary Recursion function Fibonacci ( n ) { if ( n is less than or equal to 1 ) then return n else return Fibonacci ( n - 2 ) + Fibonacci ( n - 1 ) } /* Compute the n-th Fibonacci number */ long fib ( long n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); }

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 322 HeadPtr Copy List struct LinkedListRec { int count; Node* headPtr; }; typedef struct LinkedListRec List; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 323 #include linkList.h Node* copyNodes(Node* oldNodePtr);

void copyList(List* newListPtr, List* oldListPtr) { if (listEmpty(oldListPtr)) { initializeList(newListPtr); } else { newListPtr->headPtr = copyNodes(oldListPtr->headPtr); newListPtr->count = oldListPtr->count; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 324 Node* copyNodes(Node* oldNodePtr) { Node* newNodePtr = NULL: if (oldNodePtr != NULL)

{ newNodePtr = makeNode(oldNodePtr->value); newNodePtr->nextPtr = copyNodes(oldNodePtr->nextPtr); } return newNodePtr; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 325 Copy Nodes OldNodePtr NewNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 326 Copy Nodes

OldNodePtr NewNodePtr NewNodePtr->next is set to the Result of calling copy nodes on The remainder of the list copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 327 Copy Nodes OldNodePtr NewNodePtr NewNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 328

Copy Nodes OldNodePtr NULL NewNodePtr NewNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE NewNodePtr 329 Copy Nodes OldNodePtr NewNodePtr NewNodePtr

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 330 Copy Nodes OldNodePtr NewNodePtr copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 331 Recursion Process Every recursive process consists of: 1. A base case. 2. A general method that reduces to the base case. copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 332 Types of Recursion Direct. Indirect. Linear. n-ary (Unary, Binary, Ternary, ) copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 333 Stacks Every recursive function can be implemented using a stack and iteration.

Every iterative function which uses a stack can be implemented using recursion. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 334 double power(double x, int n) { double tmp = 1; x = 2, n = 5 tmp = 1 if (n > 0) { tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; }

else { tmp = tmp*tmp*x; } } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 335 double power(double x, int n) { double tmp = 1; if (n > 0) { x = 2, n = 5 tmp = 1 x = 2, n = 2

tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; } tmp = 1 } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 336 double power(double x, int n) {

double tmp = 1; if (n > 0) { tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; } x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 1 x = 2, n = 1 tmp = 1 }

return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 337 double power(double x, int n) { double tmp = 1; if (n > 0) { tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; }

x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 1 x = 2, n = 1 tmp = 1 x = 2, n = 0 tmp = 1 } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 338 double power(double x, int n) { double tmp = 1; if (n > 0) {

tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; } x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 1 x = 2, n = 1 tmp = 1*1*2 =2 } return tmp; }

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 339 double power(double x, int n) { double tmp = 1; if (n > 0) { tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; } x = 2, n = 5 tmp = 1

x = 2, n = 2 tmp = 2*2 =4 } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 340 double power(double x, int n) { double tmp = 1; x = 2, n = 5 tmp = 4*4*2 = 32 if (n > 0) {

tmp = power(x, n/2); if (n % 2 == 0) { tmp = tmp*tmp; } else { tmp = tmp*tmp*x; } } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 341 module power(x, n) n = 5, x = 2 { create a Stack

initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Stack 342 module power(x, n) n = 5, x = 2

{ create a Stack initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Stack 5

343 module power(x, n) n = 2, x = 2 { create a Stack initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

Stack 2 5 344 module power(x, n) n = 1, x = 2 { create a Stack initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x}

} } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Stack 1 2 5 345 module power(x, n) n = 0, x = 2 { create a Stack tmp = 1 initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2

} tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Stack 1 2 5 346 module power(x, n) n = 0, x = 2 {

create a Stack tmp = 2 initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Stack 2 5

347 module power(x, n) n = 0, x = 2 { create a Stack tmp = 4 initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE Stack 5 348 module power(x, n) n = 0, x = 2 { create a Stack tmp = 32 initialize a Stack loop{ if (n == 0) then {exit loop} push n onto Stack n = n/2 } tmp = 1 loop { if (Stack is empty) then {return tmp} pop n off Stack

if (n is even) {tmp = tmp*tmp} else {tmp = tmp*tmp*x} } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Stack 349 double power(double x, int n) { double tmp = 1; Stack theStack; initializeStack(&theStack); while (n != 0) { push(&theStack, n); n /= 2; } while (!stackEmpty(&theStack)) { n = pop(&theStack); if (n % 2 == 0)

{ tmp = tmp*tmp;} else { tmp = tmp*tmp*x;} } return tmp; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 350 Disadvantages May run slower. Compilers Inefficient Code May use more space. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 351

Advantages More natural. Easier to prove correct. Easier to analysis. More flexible. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 352 Free List Non Recursive Head 0x2000 0x258a

0x4c68 /* Delete the entire list */ void FreeList(Node* head){ Node* next; while (head != NULL) { next=head->next; free(head); head=next; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 353 Free List Non Recursive head 0x2000 next

0x258a 0x4c68 /* Delete the entire list */ void FreeList(Node* head){ Node* next; while (head != NULL) { next=head->next; free(head); head=next; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 354 Free List Non Recursive head next

0x258a 0x4c68 /* Delete the entire list */ void FreeList(Node* head){ Node* next; while (head != NULL) { next=head->next; free(head); head=next; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 355 Free List Non Recursive head next

NULL 0x4c68 /* Delete the entire list */ void FreeList(Node* head){ Node* next; while (head != NULL) { next=head->next; free(head); head=next; } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 356 Free List Non Recursive head next NULL /* Delete the entire list */

void FreeList(Node* head){ Node* next; while (head != NULL) { next=head->next; free(head); head=next; } Has local variables on the stack. This is performing two assignments and one comparison per iteration. } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 357 Free List Head /* Delete the entire list */

void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 358 Free List list 0x2000 0x258a /* Delete the entire list */ void FreeList(Node* list) {

if (list==NULL) return; FreeList(list->next); free(list); } 0x4c68 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 359 Free List list 0x2000 0x258a

/* Delete the entire list */ void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list); } 0x4c68 0x258a 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 360 Free List 0x2000

0x258a /* Delete the entire list */ void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list); } list 0x4c68 0x4c68 0x258a 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

361 Free List 0x2000 0x258a /* Delete the entire list */ void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list); } list 0x4c68 NULL

0x4c68 0x258a 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 362 Free List 0x2000 0x258a /* Delete the entire list */ void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list);

} list 0x4c68 0x4c68 0x258a 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 363 Free List list 0x2000 0x258a

/* Delete the entire list */ void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list); } 0x258a 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 364 Free List list 0x2000

/* Delete the entire list */ void FreeList(Node* list) { if (list==NULL) return; FreeList(list->next); free(list); } 0x2000 Stack in memory copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 365 Free List Head 0x2000 /* Delete the entire list */

void FreeList(Node* list) { Has no local variables on the if (list==NULL) stack. This is performing one return; assignment and one FreeList(list->next); comparison per function call. free(list); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 366 Revision Recursion copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

367 Overview Trees. Terminology. Traversal of Binary Trees. Expression Trees. Binary Search Trees. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 368 Trees

Family Trees. Organisation Structure Charts. Program Design. Structure of a chapter in a book. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 369 Parts of a Tree copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 370 Parts of a Tree nodes

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 371 Parts of a Tree parent node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 372 Parts of a Tree child nodes parent node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

373 Parts of a Tree child nodes parent node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 374 Parts of a Tree root node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 375

Parts of a Tree leaf nodes copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 376 Parts of a Tree sub-tree copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 377 Parts of a Tree sub-tree copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

378 Parts of a Tree sub-tree copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 379 Parts of a Tree sub-tree copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 380 Binary Tree Each node can have at most 2 children copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

381 Traversal Systematic way of visiting all the nodes. Methods: Preorder, Inorder, and Postorder They all traverse the left subtree before the right subtree. The name of the traversal method depends on when the node is visited. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 382 Preorder Traversal Visit the node. Traverse the left subtree. Traverse the right subtree. copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 383 Example: Preorder 43 31 64 20 40 28 33 56 47 89 59

43 31 20 28 40 33 64 56 47 59 89 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 384 Inorder Traversal Traverse the left subtree. Visit the node. Traverse the right subtree. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 385 Example: Inorder 43 31 64 20

40 28 33 56 47 89 59 20 28 31 33 40 43 47 56 59 64 89 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 386 Postorder Traversal Traverse the left subtree. Traverse the right subtree. Visit the node.

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 387 Example: Postorder 43 31 64 20 40 28 33 56 47 89 59

28 20 33 40 31 47 59 56 89 64 43 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 388 Expression Tree A Binary Tree built with operands and operators. Also known as a parse tree. Used in compilers. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 389 Example: Expression Tree + / 1

/ 3 * 6 1/3 + 4 7 6*7 / 4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 390 Notation Preorder Prefix Notation Inorder

Infix Notation Postorder Postfix Notation copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 391 Example: Infix + / / 1 3 * 4

6 1 / 3 + 6 7 * copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 7 /

4 392 Example: Postfix + / / 1 * 3 6 4 7 Recall: Reverse Polish Notation 1

3 / 6 7 * copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 4 / + 393 Example: Prefix +

/ / 1 3 * 6 + / 1 3 / *

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 4 7 6 7 4 394 Binary Search Tree A Binary Tree such that: Every node entry has a unique key. All the keys in the left subtree of a node are less than the key of the node. All the keys in the right subtree of a node are greater than the key of the node. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

395 Example 1: key is an integer 43 31 64 20 40 28 33 56 47 copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 89 59 396 Example 1: key is an integer 43 31 64 20 40 28 33

56 47 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89 59 397 Insert Create new node for the item. Find a parent node. Attach new node as a leaf. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 398 Insert Example:

57 43 31 64 20 40 28 33 56 47 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89 59

399 Insert Example: 57 43 31 64 20 40 28 33 56 47 89 59

57 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 400 Search: Checklist if target key is less than current nodes key, search the left sub-tree. else, if target key is greater than current nodes key, search the right sub-tree. returns: if found, pointer to node containing target key. otherwise, NULL pointer. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 401 Search Example:

59 43 31 64 20 40 28 33 56 47 59 57 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89

found 402 Search Example: 61 43 31 64 20 40 28 33 56 47

59 57 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89 failed 403 Revision Binary Tree Preorder, Inorder, Postorder Traveral Expression Trees Prefix, Infix, and Postfix notation Insert and Search

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 404 Overview Binary Search Trees. Hash Tables. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 405 Recall - Binary Search Tree A Binary Tree such that: Every node entry has a unique key. All the keys in the left subtree of a node are less than the key of the node. All the keys in the right subtree of a node are greater than the key of the node.

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 406 Example 1: key is an integer 43 31 64 20 40 28 33 56 47

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89 59 407 Example 2: key is a string Fred Dan Alan Bill Mary Eve Eric

Kate Greg copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE Sue Len 408 Binary Tree Node entry link to right child node link to left child node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 409

Binary Search Tree Node Example 1: struct TreeNodeRec { int key; struct TreeNodeRec* struct TreeNodeRec* leftPtr; rightPtr; }; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 410 Binary Search Tree Node Example 2: #define MAXLEN 15

struct TreeNodeRec { char key[MAXLEN]; struct TreeNodeRec* struct TreeNodeRec* leftPtr; rightPtr; }; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 411 Recall: maximum string length is fixed #define MAXLEN 15

struct TreeNodeRec { char key[MAXLEN]; struct TreeNodeRec* struct TreeNodeRec* leftPtr; rightPtr; }; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 412 Example 3: struct TreeNodeRec { char* key; struct TreeNodeRec*

struct TreeNodeRec* leftPtr; rightPtr; }; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 413 Recall: Allows strings of arbitrary length. Memory needs to be allocated dynamically before use. struct TreeNodeRec { char* key;

Use strcmp to compare strings. struct TreeNodeRec* struct TreeNodeRec* left; right; }; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 414 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 415 Book Record

struct BookRec { char* author; char* title; char* publisher; key /* etc.: other book information. */ }; typedef struct BookRec Book; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 416 Example 4: Binary Search Tree Node struct TreeNodeRec { Book info;

struct TreeNodeRec* struct TreeNodeRec* leftPtr; rightPtr; }; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 417 Tree Node struct TreeNodeRec { float key; struct TreeNodeRec* struct TreeNodeRec* leftPtr; rightPtr;

}; typedef struct TreeNodeRec TreeNode; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 418 #ifndef TREE_H #define TREE_H struct TreeNodeRec { float struct TreeNodeRec* struct TreeNodeRec* }; key; leftPtr; rightPtr; typedef struct TreeNodeRec TreeNode; TreeNode* makeTreeNode(float value);

TreeNode* insert(TreeNode* nodePtr, float item); TreeNode* search(TreeNode* nodePtr, float item); void printInorder(const TreeNode* nodePtr); void printPreorder(const TreeNode* nodePtr); void printPostorder(const TreeNode* nodePtr); #endif copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 419 MakeNode parameter: item to be inserted steps: allocate memory for the new node check if memory allocation is successful if so, put item into the new node

set left and right branches to NULL returns: pointer to (i.e. address of) new node copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 420 TreeNode* makeTreeNode(float value) { TreeNode* newNodePtr = NULL; newNodePtr = (TreeNode*)malloc(sizeof(TreeNode)); if (newNodePtr == NULL) { fprintf(stderr, Out of memory\n); exit(1); } else { newNodePtr->key = value; newNodePtr->leftPtr = NULL; newNodePtr->rightPtr = NULL;

} return newNodePtr; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 421 value 3.3 newNodePtr NULL newNodePtr 0x2000 newNodePtr

0x2000 0x2000 0x2000 3.3 NULL copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE NULL 422 Inorder Inorder traversal of a Binary Search Tree always gives the sorted order of the keys. void printInorder(TreeNode* nodePtr) { initially, pointer to root node

} copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 423 Inorder Inorder traversal of a Binary Search Tree always gives the sorted order of the keys. void printInorder(TreeNode* nodePtr) { traverse left sub-tree visit the node traverse right sub-tree } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 424 Inorder Inorder traversal of a Binary Search Tree always gives the sorted order of the keys.

void printInorder(TreeNode* nodePtr) { printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 425 Inorder Inorder traversal of a Binary Search Tree always gives the sorted order of the keys. void printInorder(TreeNode* nodePtr) { if (nodePtr != NULL) { printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); } }

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 426 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 427 Inorder nodePtr

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 428 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE

} 429 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 430 Inorder nodePtr void printInorder(TreeNode* nodePtr){

if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 431 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE }

432 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 433 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){

printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 434 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE }

435 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 436 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr);

printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 437 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 438

Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 439 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key);

printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 440 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 441

Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 442 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr);

copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 443 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 444 Inorder

nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 445 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA

} C.N,CS&E dept,SJCE } 446 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 447 Inorder nodePtr

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 448 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA }

C.N,CS&E dept,SJCE } 449 Inorder nodePtr void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf( %f, nodePtr->key); printInorder(nodePtr->rightPtr); copy right (version1.0) SUNITHA } C.N,CS&E dept,SJCE } 450 Search Example:

59 43 31 64 20 40 28 33 56 47 59 57 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89

found 451 Search Example: 61 43 31 64 20 40 28 33 56 47

59 57 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 89 failed 452 Search: Checklist if target key is less than current nodes key, search the left sub-tree. else, if target key is greater than current nodes key, search the right sub-tree. returns: if found, or if target key is equal to current nodes key, a pointer to node containing target key. otherwise, NULL pointer. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

453 TreeNode* search(TreeNode* nodePtr, float target) { if (nodePtr != NULL) { if (target < nodePtr->key) { nodePtr = search(nodePtr->leftPtr, target); } else if (target > nodePtr->key) { nodePtr = search(nodePtr->rightPtr, target); } } return nodePtr; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 454

Function Call to Search /* other bits of code omitted */ printf(Enter target ); scanf(%f, &item); if (search(rootPtr, item) == NULL) { printf(Item was not found\n); } else { printf(Item found\n); } /* and so on */ copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 455 Search

nodePtr Find 0.7 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){

if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 456 Search nodePtr Find 0.7 1.0 0.6 0.3 1.9 0.8

0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE }

457 Search nodePtr Find 0.7 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 458 Search nodePtr Find 0.7 1.0 0.6 0.3

1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE } 459 Search nodePtr Find 0.5 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 1.1

2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 460 Search nodePtr Find 0.5

1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target);

} return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 461 Search nodePtr Find 0.5 1.0 0.6 0.3 1.9 0.8 0.4 0.7

1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 462 Search nodePtr

Find 0.5 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key)

nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 463 Search nodePtr Find 0.5 1.0 0.6 0.3 1.9 0.8

0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE } 464

Insert Example: 57 43 31 64 20 40 28 33 56 47 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

89 59 465 Insert Example: 57 43 31 64 20 40 28 33 56 47

89 59 57 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 466 Insert Create new node for the item. Find a parent node. Attach new node as a leaf. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 467 Insert: Recursive parameters:

pointer to current node (initially: root node). item to be inserted. If current node is NULL Create a new node and return it. Else if items key is less (greater) than current nodes key: otherwise, let the left (right) child node be the current node, setting the parent left (right) link equal that node, and repeat recursively. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 468 TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) { nodePtr = makeTreeNode(item);

} else if (item < nodePtr->key) { nodePtr->leftPtr = insert(nodePtr->leftPtr, item); } else if (item > nodePtr->key) { nodePtr->rightPtr = insert(nodePtr->rightPtr, item); } return nodePtr; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 469 Function Call to Insert /* other bits of code omitted */ printf(Enter number of items ); scanf(%d, &n);

for (i = 0; i < n; i++) { scanf(%f, &item); rootPtr = insert(rootPtr, item); } /* and so on */ copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 470 Insert nodePtr Insert 0.9 1.0 0.6 0.3 1.9 0.8 0.4

0.7 1.4 1.1 2.7 1.8 TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); copy right (version1.0) SUNITHA return nodePtr; C.N,CS&E dept,SJCE } 471

Insert nodePtr Insert 0.9 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8

TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); copy right (version1.0) SUNITHA return nodePtr; C.N,CS&E dept,SJCE } 472 Insert nodePtr Insert 0.9 1.0 0.6 0.3

1.9 0.8 0.4 0.7 1.4 1.1 2.7 1.8 TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); copy right (version1.0) SUNITHA

return nodePtr; C.N,CS&E dept,SJCE } 473 Insert nodePtr Insert 0.9 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4

1.1 2.7 1.8 TreeNode* insert(TreeNode* nodePtr, float item) { if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); copy right (version1.0) SUNITHA return nodePtr; C.N,CS&E dept,SJCE } 474 Insert nodePtr

Insert 0.9 1.0 0.6 0.3 1.9 0.8 0.4 0.7 1.4 0.9 1.1 2.7 1.8 TreeNode* insert(TreeNode* nodePtr, float item) {

if (nodePtr == NULL) nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); copy right (version1.0) SUNITHA return nodePtr; C.N,CS&E dept,SJCE } 475 Sorting To sort a sequence of items: Insert items into a Binary Search Tree. Then Inorder Traverse the tree. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 476

Sorting: Analysis Average Case: O(n log(n)) ~ log2 n Insert (i+1)th item: ~ log2(i) comparisons copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 477 Sort Sort the following list into a binary search tree 1.0 2.5 0.5 0.7 3.6

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2.1 478 Sort 1.0 Sort the following list into a binary search tree 1.0 2.5 0.5 0.7 3.6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

2.1 479 Sort 1.0 2.5 Sort the following list into a binary search tree 1.0 2.5 0.5 0.7 3.6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2.1

480 Sort 1.0 0.5 2.5 Sort the following list into a binary search tree 1.0 2.5 0.5 0.7 3.6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2.1

481 Sort 1.0 0.5 2.5 0.7 Sort the following list into a binary search tree 1.0 2.5 0.5 0.7 3.6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

2.1 482 Sort 1.0 0.5 2.5 0.7 3.6 Sort the following list into a binary search tree 1.0 2.5 0.5 0.7 3.6

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2.1 483 Sort 1.0 0.5 2.5 0.7 2.1 3.6 Sort the following list into a binary search tree 1.0 2.5 0.5

0.7 3.6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2.1 484 Sorting: Analysis Worst Case: O(n2) Example: Insert: 1, 3, 7, 9, 11, 15 Insert (i+1)th item: ~ i comparisons copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 485 Revision

Binary Search Tree Make Tree Node, Insert item, Search for an item, and Print Inorder. Tree sort. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 486 Overview Divide and Conquer Merge Sort Quick Sort copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 487 Divide and Conquer Recall: Binary Search

Search Search Search copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 488 Divide and Conquer Sort Sort Sort Sort Sort Sort copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE Sort 489 Divide and Conquer Combine Combine Combine copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 490 Divide and Conquer module sort(array) { if (size of array > 1) {

split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) } } copy right (version1.0) SUNITHA 491 C.N,CS&E dept,SJCE Divide and Conquer module sort(array) { if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) } } copy right (version1.0) SUNITHA 492

C.N,CS&E dept,SJCE Divide and Conquer module sort(array) { if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) } } copy right (version1.0) SUNITHA 493 C.N,CS&E dept,SJCE Divide and Conquer module sort(array) { if (size of array > 1) { split(array, firstPart, secondPart)

sort(firstPart) sort(secondPart) combine(firstPart, secondPart) } } copy right (version1.0) SUNITHA 494 C.N,CS&E dept,SJCE Divide and Conquer module sort(array) { if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) } } copy right (version1.0) SUNITHA 495 C.N,CS&E dept,SJCE

Merge Sort Sort Sort Merge copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 496 Merge Sort array: tmpArrayPtr: size tmp: copy right (version1.0) SUNITHA

C.N,CS&E dept,SJCE 497 Merge Sort array[0] array[mid] mid (size - mid) firstPart : array secondPart : array + mid copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 498 Merge Sort array:

mergeList tmp: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 499 Merge Sort array: tmp: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 500 Merge Sort array:

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 501 void mergeSort(float array[], int size) { int* tmpArrayPtr = (int*)malloc(size*sizeof(int)); if (tmpArrayPtr != NULL) { mergeSortRec(array, size, tmpArrayPtr); } else { fprintf(stderr, Not enough memory to sort list.\n); exit(1); } free(tmpArrayPtr); } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

502 void mergeSortRec(float array[], int size, float tmp[]) { int i; int mid = size/2; if (size > 1) { mergeSortRec(array, mid, tmp); mergeSortRec(array+mid, size-mid, tmp); mergeArrays(array, mid, array+mid, size-mid, tmp); for (i = 0; i < size; i++) { array[i] = tmp[i]; } } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 503

Example: a: 3 5 mergeArrays 15 28 30 b: 6 aSize: 5 10 14 22 43 50 bSize: 6 tmp: copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 504

Example: a: 3 5 mergeArrays 15 28 30 i=0 b: 6 10 14 22 43 50 j=0 tmp: k=0 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

505 Example: a: 3 5 mergeArrays 15 28 30 i=0 b: 6 10 14 22 43 50 j=0 tmp: 3 k=0

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 506 Example: a: 3 5 mergeArrays 15 28 30 i=1 b: 6 10 14 22 43 50 j=0

tmp: 3 5 k=1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 507 Example: a: 3 5 mergeArrays 15 28 30 i=2 b: 6

10 14 22 43 50 j=0 tmp: 3 5 6 k=2 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 508 Example: a: 3 5

mergeArrays b: 6 15 28 30 i=2 10 14 22 43 50 j=1 tmp: 3 5 6 10 k=3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

509 Example: a: 3 5 mergeArrays 15 28 30 b: 6 i=2 10 14 22 43 50 j=2 tmp: 3 5

6 10 14 k=4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 510 Example: a: 3 5 mergeArrays 15 28 30 i=2

b: 6 10 14 22 43 50 j=3 tmp: 3 5 6 10 14 15 k=5 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 511 Example: a: 3

5 mergeArrays 15 28 30 i=3 b: 6 10 14 22 43 50 j=3 tmp: 3 5 6 10 14 15 22

k=6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 512 Example: a: 3 5 mergeArrays 15 28 30 i=3 b: 6 10 14 22 43 50 j=4

tmp: 3 5 6 10 14 15 22 28 k=7 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 513 Example: a: 3 5 mergeArrays

15 28 30 i=4 b: 6 10 14 22 43 50 j=4 tmp: 3 5 6 10 14 15 22 28 30 k=8 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 514

Example: a: 3 5 mergeArrays 15 28 30 i=5 b: 6 10 14 22 43 50 j=4 Done. tmp: 3

5 6 10 14 15 22 28 30 43 50 k=9 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 515 void mergeArrays(float a[],int aSize,float b[],int bSize,float tmp[]) { int k, i = 0, j = 0; for (k = 0; k < aSize + bSize; k++) { if (i == aSize) { tmp[k] = b[j]; j++; }

else if (j == bSize) { tmp[k] = a[i]; i++; } else if (a[i] <= b[j]) { tmp[k] = a[i]; i++; } else { tmp[k] = b[j]; j++; } copy right (version1.0) SUNITHA } } C.N,CS&E dept,SJCE 516 Merge Sort and Linked Lists Sort

Sort Merge copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 517 Merge Sort Analysis Most of the work is in the merging. Takes O(n log(n)) Uses more space than other sorts. Useful for linked lists. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

518 Quick Sort Partition x

array: 5 Quick Sort 89 35 10 24 15 37 13 20 17 70 size: 11 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 520 Example: array: 5 Quick Sort 89 35 14 24 15 37 13 20 7 70

pivot element copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 521 Quick Sort Example: array: 5 89 35 14 24 15 37 13 20 7 70

7 70 partition: 5 89 35 14 24 15 37 13 20 7 14 5 13 15 35 37 89 20 24 70 index: 4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 522

Quick Sort Example: index: 4 array: 7 14 5 13 15 35 37 89 20 24 70 index (size - index - 1) copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 523 Quick Sort

Example: array[0] 7 14 array[index + 1] 5 13 15 35 37 89 20 24 70 index (size - index - 1) firstPart : array secondPart : array + index + 1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

524 Quick Sort void quickSort(float array[], int size) { int index; if (size > 1) { index = partition(array, size); quickSort(array, index); quickSort(array+index+1, size - index - 1); } } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 525 0 Partition: Checklist p

p p p x

Partition mid: 4 0 array: 5 89 35 14 24 15 37 13 20 15 89 35 14 24 5 37 13 20 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 7 70 7 70 527

Partition Example: 0 array: 15 89 35 14 24 5 37 13 20 7 70 k=1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 528

Partition Example: index:0 array: 15 89 35 14 24 5 37 13 20 7 70 k:1 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 529 Example: Partition

index:0 array: 15 89 35 14 24 5 37 13 20 7 70 k:2 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 530 Example: Partition index:0 array: 15 89 35 14 24 5

37 13 20 7 70 k:3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 531 Partition Example: index:1 array: 15 14 89 35 89 14 24 5

37 13 20 7 70 k:3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 532 Partition Example: index:1 array: 15 14 35 89 24 5 37 13 20 7

70 k:4 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 533 Partition Example: index:1 array: 15 14 35 89 24 5 37 13 20 7 70

k:5 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 534 Example: Partition index:2 array: 15 14 35 5 89 24 35 5 37 13 20 7 70 k:5 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

535 Partition Example: index:2 array: 15 14 5 89 24 35 37 13 20 7 70 k:6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 536 Partition

Example: index:2 array: 15 14 5 89 24 35 37 13 20 k:7 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 7 70 etc... 537 Partition

Example: index:4 array: 15 14 5 13 7 35 37 89 20 24 70 k:11 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 538 Partition Example: index:4

array: 15 14 5 13 7 35 37 89 20 24 70 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 539 Partition Example: index:4 array: 15 7 14 5 13 15 7 35 37 89 20 24 70

x < 15 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 15 <= x 540 Example: pivot now in correct position array: 15 7 14 5 13 15 7 35 37 89 20 24 70 x < 15 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

15 <= x 541 Example: 7 14 5 13 15 35 37 89 20 24 70 Sort 7 14 Sort 5

13 35 37 89 20 24 70 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 542 int partition(float array[], int size) { int k; int mid = size/2; int index = 0; swap(array, array+mid); for (k = 1; k < size; k++) { if (list[k] < list[0]) { index++; swap(array+k, array+index); } }

swap(array, array+index); return index; } copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 543 Quick Sort Analysis Most of the work done in partitioning. Need to be careful of choice of pivot. Example: 2, 4, 6, 7, 3, 1, 5 Average case takes O(n log(n)) time. Worst case takes O(n2) time. copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 544 Revision

Merge Sort Quick Sort copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 545

Recently Viewed Presentations

  • Università degli Studi del Piemonte Orientale &quot;Amedeo Avogadro&quot;

    Università degli Studi del Piemonte Orientale "Amedeo Avogadro"

    Università degli Studi del Piemonte Orientale "Amedeo Avogadro" Presentation WEM Lisbon, 22nd May 2003 Gisella Favagrossa, Paolo Pomati The University The University of Eastern Piedmont "Amedeo Avogadro" was established as an autonomous institution in 1998 and, after its first five...
  • Constitutional Criminal Procedure

    Constitutional Criminal Procedure

    2. Voting systems and procedures. Cycling, Social Choice, and the Arrow's Impossibility Theorem:. Suppose there are 3 judges in a hypothetical case regarding a recently passed health care law that forces employers to include abortion related services in the health...
  • Block Diagrams - UToledo Engineering

    Block Diagrams - UToledo Engineering

    Analogous Physical Systems BIOE 4200 Creating Mathematical Models Break down system into individual components or processes Need to model process outputs as function of inputs and process states Models can be obtained experimentally Measure output using a range of inputs...
  • OMG SOA SIG Activity Debrief

    OMG SOA SIG Activity Debrief

    IBM Adaptive Cap Gemini EDS HP Model Driven Solutions Telelogic BAE Systems Azora everware-cbdi France Telecom R&D The Thales Group European Software Institute, Softteam, Rhysome and MIDt Agenda SOA Challenge OMG SOA SIG: Mission & Participants OMG's approach to SOA...
  • The Last Laugh - Photos by Kim

    The Last Laugh - Photos by Kim

    By Wilfred Owen. The Last Laugh. The Title. He who laughs last, laugh loudest. Subject of the Poem. The Deaths of soldiers. The Institutes and people the soldiers often refer for comfort. The machines of war. The Futility of the...
  • 1 Simpozionul Educaie prin ah Valorile educative ale

    1 Simpozionul Educaie prin ah Valorile educative ale

    În plan educativ:șahul crează modele de studiu, stimulează învățarea pe baza unei metode și realizează o strânsă conexiune între dorința de progres și cunoștințele acumulate.. În plan. ul. logic. ii: întimpul unei partide de șah jucătorul ia decizii bazându-se pe...
  • E. coli O157: Pre-harvest opportunities &amp; Challenges

    E. coli O157: Pre-harvest opportunities & Challenges

    E. coli O157:H7 Summer season prevalence Model to Compare Prevalence of Cattle During Summer, Winter, and with intervention (Summer) Data-driven Simulation. Source, Dave Smith, UNL Model to Compare Prevalence of Cattle During Summer, Winter, and with intervention (Summer) Data-driven Simulation.
  • Cornerstone: Creating Success through Positive Change 6th edition

    Cornerstone: Creating Success through Positive Change 6th edition

    Topic: Listening/Note-Taking ... Cornerstones for Career College Success, 3e Three Note-Taking Systems Outline technique Cornell (split-page) technique Mapping technique ©Pearson Education, Inc. (2013) Sherfield/Moody, Cornerstones for Career College Success, 3e Outline Technique ©Pearson ...