Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M.

Similar presentations


Presentation on theme: "1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M."— Presentation transcript:

1

2 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M.

3 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 2 Data Structures and Algorithms Programs. Different problems. Operations. Size of data. Resources available.

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

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

6 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 5 Basic Data types in C int char float double

7 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 6 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 doesn’t work in Borland) In Borland programs, use #define to define the constants true and false

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

9 #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; } For Borland use #define or const int

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

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

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

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

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

15 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); } Recall: Function call

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

17 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 16 Review - Multidimensional Arrays Arrays of arrays. All the elements are of the same type. An element: array2D[row][column] array2D:

18 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; }

19 Recall: Global variable Local variable 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; }

20 Recall: 2-dimensional array of int 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; }

21 Recall: Index goes from 0 to 12 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; }

22 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 21 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); Data is read in from stdin using the scanf() function. scanf("%s %f %c %d", name, &age, &gender, &idNumber); Format control string Review – Input/Output Conversion specifiers Pointers to variables where input will be stored Variables containing data to be printed

23 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 22 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 Review – Input/Output

24 #include int main() { int day; int month; int year; char name[30]; printf(“Enter your name:\n”> scanf(“%s”, name); /* skipping spaces */ printf(“Hi %s. Enter birthdate as: dd mm yyyy\n”, name); scanf("%d %d %d", &day, &month, &year); /* alternative */ printf(“Hi %s. Enter birthdate as: dd-mm-yyyy\n”, name); scanf("%d-%d-%d", &day, &month, &year); return 0; } Note: no ampersand for strings Conversion specifier Literal characters

25 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 24 Strings : array of characters Example: 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) Concatenation - strcat(dest, string2) Comparison - strcmp(string1, string2) Max length including ‘\0’ Copies string2 onto the end of the destination string Returns: positive if string1 sorts after string2, 0 if they are the same string negative if string1 sorts before string2 Review - Strings

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

27 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); } strcat(string1, “ juice”); printf(“%s\n”, string1); return 0; } Prints the order which the two strings sort, alphabetically. Note: To scan within a string use: sscanf(string1, “%d”, int1);

28 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 27 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().

29 #include #define MAXLEN 100 int main() { FILE *inputfile = NULL; FILE *outputfile = NULL; char name[MAXLEN]; int count; float mark; 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; } Mode r : read w : write a : append Associate a file handler for every file to be used. fopen() returns NULL if an error occurs

30 fscanf() returns the number of values read and converted count = 0; while ( fscanf(inputfile, "%s", name ) == 1 ) { count++; 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"); return 1; } printf("\n"); printf("Number of names read: %d\n", count); fclose(inputfile); fclose(outputfile); return 0; } fprintf() returns the number of successfully written or negative if an error occurs

31 #include #define MAXLEN 100 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; } while(fgets(line, MAXLEN, inputfile) != NULL) { count++; } printf(“Number of lines: %d”, count); fclose(inputfile); return 0; } To read in a line, use fgets(). fgets() returns NULL if end of file is reached. fgets(string, length, filehandle) What would happen if you tried to count the number of lines again, once the end of the file has been reached?

32 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 31 Review - struct Members may have different types. structname.membername structs are also known as “records,” and members as “fields” structname:

33 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 32 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.

34 #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student; Example :

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

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

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

38 Recall: Data type New type name #include #define MAXNAME 80 struct StudentRec { char name[MAXNAME]; int mark; }; typedef struct StudentRec Student;

39 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); }

40 Recall: An instance of the struct A member of a struct variable“Package” 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); }

41 #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]); }

42 Recall: Array of instances of structs Assignment Member of an array element #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]); }

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

44 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 43 Overview Revision of Pointers Basic Pointer Arithmetic Pointers and Arrays

45 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 44 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; int x; addr of x 1 0x2000 0x9060

46 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 45 Pointer Operations 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 Type object; Type* aPtr;

47 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 46 Pointers and Function Arguments x: 1 y: 2 swap x: 2 y: 1

48 #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

49 #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); } 1 2 x: y: Solution 1 0x2000 0x2010

50 #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); } 1 2 x: y: 1 2 a: b: tmp: Solution 1 0x2000 0x2010 0x2060 0x2038 0x2040

51 #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); } 1 2 x: y: 1 2 a: b: 1 tmp: Solution 1 0x2000 0x2010 0x2060 0x2038 0x2040

52 #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); } 1 2 x: y: 2 2 a: b: 1 tmp: Solution 1 0x2000 0x2010 0x2060 0x2038 0x2040

53 #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); } 1 2 x: y: 2 1 a: b: 1 tmp: Solution 1 0x2000 0x2010 0x2060 0x2038 0x2040

54 #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); } 1 2 x: y: Solution 1 0x2000 0x2010

55 #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

56 #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); } 1 2 x: y: Solution 2 0x2000 0x2010

57 #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); } 1 2 x: y: addr of x addr of y a: b: tmp: Solution 2 0x2000 0x2010 0x2060 0x2038 0x2040

58 #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); } 1 2 x: y: addr of x addr of y a: b: 1 tmp: Solution 2 0x2000 0x2010 0x2060 0x2038 0x2040

59 #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); } 2 2 x: y: addr of x addr of y a: b: 1 tmp: Solution 2 0x2000 0x2010 0x2060 0x2038 0x2040

60 #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); } 2 1 x: y: addr of x addr of y a: b: 1 tmp: Solution 2 0x2000 0x2010 0x2060 0x2038 0x2040

61 #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); } 2 1 x: y: Solution 2 0x2000 0x2010

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

63 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 62 struct DataBaseRec { }; typedef struct DataBaseRec DataBase; /* Very Large Structure */

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

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

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

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

68 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 67 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; } return 0; } Why do you need the brackets?

69 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 68 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.

70 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 69 Pointers and Arrays 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. Type array[ size ]; Type* pPtr = array + i; Type* qPtr = array + j;

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

72 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 71 float array[5]; float* pPtr = array; float* qPtr = NULL; 0x2008 0x2004 array: pPtr: 0x20080x200C0x20100x20140x2018 01234 NULL 0x2000 qPtr: Basic Pointer Arithmetic

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

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

75 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 74 float 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]*/ 0x2018 0x2008 0x2004 array: pPtr: 0x20080x200C0x20100x20140x2018 01234 0x2010 0x2000 qPtr:

76 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 75 float array[5]; float* pPtr = array; float* qPtr = NULL; pPtr++; /* pPtr = &array[1] */ pPtr += 3; /* pPtr = &array[4] */ qPtr = array + 2; /* qPtr = &array[2] */ printf(“%d\n”, pPtr-qPtr); 0x2018 0x2008 0x2004 array: pPtr: 0x20080x200C0x20100x20140x2018 01234 0x2010 0x2000 qPtr:

77 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; }

78 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 77Revision 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

79 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 78 Next Lecture Stacks –abstract data type –main operations –implementation

80 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 79 Basic Data Structures Stacks Queues Lists

81 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 80 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.

82 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 81 A Stack Top Items on the Stack

83 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 82 Push Top After Top Before

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

85 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 84 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

86 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 85 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.

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

88 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 87 Implementation Top float entry[MAXSTACK]; int top; 0 1 2 :

89 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 88 #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

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

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

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

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

94 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 93 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; }

95 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 94 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; }

96 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 95 #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); } printf(“\n”); }

97 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 96 Revision Stack Operations on a Stack –push, pop –initialize –status: empty, full –others: clear, size Implementation.

98 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 97 Next Lecture Queue Main Operations Implementation

99 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 98 Basic Data Structures Stacks Queues Lists

100 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 99 Overview What is a Queue? Queue Operations. Applications. Linear Implementation. Circular Implementation.

101 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 100Insert Before FrontRear After FrontRear

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

103 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 102 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?

104 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 103 Applications In operating systems, e.g. printer queues, process queues, etc. Simulation programs. Algorithms.

105 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 104 Linear Implementation Front Rear 01234567

106 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 105 Insert FrontRear 01234567

107 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 106 Insert FrontRear 01234567

108 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 107 Delete FrontRear 01234567 This comes off the queue

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

110 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 109 Insert FrontRear 01234567

111 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 110 Insert FrontRear 01234567 NO SPACE HERE

112 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 111 Insert FrontRear 01234567 SPACE HERE

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

114 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 113 Circular Implementation FrontRear 01234567

115 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 114 Insert FrontRear 01234567

116 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 115 #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

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

118 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 117 #include #include “queue.h” void initializeQueue(Queue* queuePtr) { queuePtr -> count = 0; queuePtr -> front = 0; queuePtr -> rear = MAXQUEUE-1; } rear:...... entry: Queue: addr of Queue queuePtr: 19 count: 0 front: 0

119 bool queueEmpty(const Queue* queuePtr) { if (queuePtr->count <= 0) { return true; } else { return false; }

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

121 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++; }

122 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; }

123 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 122Revision Queue Main Operations Implementation.

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

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

126 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 125 Lists SEALFOXDEERAPEEMU 01342

127 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 126 Insertion SEALFOXDEERAPE 0132 EMU Inserted at position 2 SEALFOXDEERAPE 0134 EMU 2 Before: After:

128 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 127 Deletion SEALFOXDEERAPE 0134 EMU 2 Delete item at position 3 SEALDEERAPE 013 EMU 2 Before: After:

129 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 128 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.

130 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 129 A List ADT 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. A sequence of elements together with these operations:

131 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 130 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.

132 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 131 A Stack ADT 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. A sequence of elements together with these operations:

133 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 132 A Queue ADT 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. A sequence of elements together with these operations:

134 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 133 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.

135 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 134 A Rational Number ADT 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. Two integers together with these operations:

136 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 135 A String ADT 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. A array of characters together with these operations:

137 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 136 Simple List Implementation 012345 APEDEERFOXSEAL EMU

138 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 137 Simple List Implementation 012345 APEDEERFOXSEAL EMU

139 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 138 Simple List Implementation 012345 APEDEERFOXSEALEMU

140 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 139 Linked List Implementation: Using Array Index DEERFOXAPESEAL 012345 130 data marks last item start link to next item

141 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 140 Linked List Implementation: Using Array Index DEERFOXAPESEAL 012345 30 start insert: EMU EMU 11

142 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 141 Linked List Implementation: Using Array Index DEERFOXAPESEAL 012345 430 start insert: EMU EMU 1

143 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 142 Linked List Implementation: Using Pointers DEERFOXAPESEAL 0x20000x20080x20100x20180x20200x2018 0x20200x20180x2000NULL start EMU 0x2008

144 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 143 Linked List Implementation: Using Pointers DEERFOXAPESEAL 0x20000x20080x20100x20180x20200x2018 0x20200x20180x2000NULL start EMU 0x2008 special pointer constant

145 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 144 Revision List –initialize, insert, delete, position, status –implementations Difference between Stacks, Queues, and Lists. ADT.

146 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 145 Overview Linked Stack. –Push –Pop Linked Queue. –Insert –Delete

147 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 146 Linked Stack Top of the Stack NULL pointer

148 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 147 #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

149 void initializeStack(Stack* stackPtr) { stackPtr->topPtr = NULL; } Initialize Stack

150 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 149 Push Top

151 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 150 Push create a new node for the item link the new node to the current top node make the new node the new top

152 void push(Stack* stackPtr, float item) { Node* newNodePtr = makeNode(item); newNodePtr->nextPtr = stackPtr->topPtr; stackPtr->topPtr = newNodePtr; } Push

153 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 152 Pop Top

154 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 153 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

155 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; }Pop

156 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 155 Linked Queue FrontRear

157 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 156 #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

158 void initializeQueue(Queue* queuePtr) { queuePtr->frontPtr = NULL; queuePtr->rearPtr = NULL; queuePtr->count = 0; } Initialize Queue

159 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 158 Insert Front Rear

160 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 159 Insert Front Rear Front Rear

161 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 160 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

162 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++; }

163 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 162 Delete Front Rear

164 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 163 Delete Front Rear Front

165 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 164 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

166 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; }

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

168 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 167 Revision Linked Stack. –Initialize, Pop, Push. Linked Queue. –Initialize, Insert,Delete

169 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 168 Overview What is Dynamic Memory ? How to find the size of objects. Allocating memory. Deallocating memory.

170 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 169 Virtual Memory Text Segment Data Segment Stack segment program instructions static and dynamic data local variables, parameters free memory

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

172 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 171 Virtual Memory Text Segment Static data Heap Stack segment memory is allocated and deallocated as needed

173 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 172 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

174 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 173 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.

175 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 174 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack

176 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 175 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b

177 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 176 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x

178 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 177 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line 16

179 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 178 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line 16 result

180 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 179 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line 16 9.9225 result

181 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 180 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack 3.15 a b x line 16 9.9225 result

182 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 181 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 9.9225 stack 3.15 a b

183 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 182 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: 9.9225 stack 3.15 a b

184 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 183 #include float square(float x) { float result; result = x * x; return result; } main() { float a = 3.15; float b; b = square(a); printf(“%f\n”, b); } 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: stack

185 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 184 #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); }

186 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 185 How much memory to allocate? The sizeof operator returns the size of an object, or type, in bytes. Usage: sizeof( Type ) sizeof Object

187 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 186 Example 1: int n; char str[25]; float x; double numbers[36]; printf(“%d\n”, sizeof(int)); printf(“%d\n”, sizeof n); n = sizeof str; n = sizeof x; n = sizeof(double); n = sizeof numbers;

188 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 187 Notes on sizeof Do not assume the size of an object, or type; use sizeof instead. In DOS: 2 bytes (16 bits) In GCC/Linux: 4 bytes (32 bits) In MIPS: 4 bytes (32 bits) Example: int n;

189 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 188 #include #define MAXNAME 80 #define MAXCLASS 100 struct StudentRec { char name[MAXNAME]; float mark; }; typedef struct StudentRec Student; Example 2:

190 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 189 int main() { int n; Student 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; } Example 2 (cont.):

191 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 190 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; }; typedef struct cardRec Card; Card hand[5]; printf(“%d\n”, sizeof(Card)); printf(“%d\n”, sizeof hand); “alignment” and “padding” 5*sizeof(Card)

192 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 191 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)

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

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

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

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

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

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

199 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 198 #include 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; } Example 2:

200 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 199 Allocating Memory NeedNeed to include stdlib.h malloc(n) returns a pointer to n bytes of memory. AlwaysAlways check if malloc has returned the NULL pointer. ApplyApply a type cast to the pointer returned by malloc.

201 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 200 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. ShouldShould free memory no longer being used.

202 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 201 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); } Example 3:

203 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 202 main() { Student* class = NULL; int n, i, best = 0; 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]); } Example 4:

204 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 203 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.

205 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 204 #include 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; } Example 5:

206 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 205 Revision sizeof malloc free Common errors.

207 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 206 Overview of Topic Review List Implementations. Nodes. Linked Stacks. Linked Queues Linked Lists. Other List Operations Today’s Lecture

208 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 207 Lists 1510316 01342

209 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 208 A List ADT 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. A sequence of elements together with these operations:

210 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 209 Insertion 1510 3 1 0132 6 Inserted at position 2 151031 0134 6 2 Before: After:

211 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 210 A List ADT 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. A sequence of elements together with these operations: List needs to be able to expand

212 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 211 Simple List Implementation 13101521 6

213 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 212 Expansion and Insertion 13101521 13101521 6 6 Copy old array, leave space for the new value

214 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 213 Disadvantages Lots of memory needs to be allocated. Lots of copying needs to be done.

215 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 214 Linked List Implementation: Using Pointers 315121 0x20000x20080x20100x20180x2020 0x20180x2000NULL start 10 0x2008 insert: 6

216 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 215 Method 1 start 315121 0x20000x20080x20100x20180x2020 0x20180x2000NULL 10 0x2008 0x30F00x30F80x31000x31080x3110 newStart 0x3118 insert: 6 13 0x30F80x31000x31080x31100x3118NULL 6101521 0x30F0 Copy old array, leave space for the new value

217 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 216 Method 2 315121 0x20000x20080x20100x20180x2020 0x20180x2000NULL start 10 0x2008 insert: 6 6 newItem 0x30F0

218 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 217 Method 2 315121 0x20000x20080x20100x20180x2020 0x30F00x20180x2000NULL start 10 0x2008 insert: 6 6 newItem 0x30F0 0x2020

219 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 218 Advantages Only a little amount of memory needs to be allocated. Only a little amount of copying needs to be done.

220 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 219 struct NodeRec { float value; struct NodeRec* nextPtr; }; typedef struct NodeRec Node; Node: nextPtr: value:

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

222 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 221 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 node’s address

223 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; }

224 #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; }

225 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 224 0x30F00x21246 firstNodePtr:lastNodePtr:item: 0x30F0 0x2124 0x2A40 1 nextPtr: value: 6 NULL nextPtr: value: 3 0x2124 nextPtr: value:

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

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

228 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 227 Linked Structure 1 3 firstNodePtr: 6

229 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 228 Linked Structure firstNodePtr:

230 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 229 Revision Node How to make a new Node Linked Structure

231 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 230 Overview Operations for Lists. Implementation of Linked Lists. Double Linked Lists.

232 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 231 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.

233 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 232 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

234 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 233 Linked List Head 0123

235 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 234 #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

236 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 235 void initializeList(List* listPtr) { listPtr->headPtr = NULL; listPtr->count = 0; } Initialize List count headPtr 0 NULL listPtr addr of list

237 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 236 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

238 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 237 Set Position Head 021 2 position

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

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

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

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

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

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

245 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 244 Insert Head 021 If we insert it at position 0. 0213 Head

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

247 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 246 Head Instead, suppose we insert it at position 1. 032 1

248 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 247 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++; }

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

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

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

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

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

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

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

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

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

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

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

260 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 259 void deleteNode(List* listPtr, int position) { Node* oldNodePtr = NULL; Node* nodePtr = NULL; if (listPtr->count > 0 && position 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); }

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

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

263 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 262 Head 0 position 0x4000 NodePtr 0x30a80x2030 Deleting – 1 st Node

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

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

266 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 265 Head 0x30a80x4000 Deleting – Middle Node 1 position 0x2030 OldNodePtr 0x2030 NodePtr

267 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 266 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. in both directionsTraverse a list, in both directions.

268 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 267 Double Linked List Current 01234

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

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

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

272 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 271 Insert at end newPtr 0x40000x30800x20300x2000 0x40000x3080 0x2030 0x2000 NULL 0x2030 0x2000 prevPtr 0x2030 currentPtr

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

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

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

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

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

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

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

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

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

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

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

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

285 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 284 Revision Linked List. Benefits of different implementations. Double Linked List.

286 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 285 Overview Selection Sort Insertion Sort Linear Search. Binary Search. Growth Rates. Implementation.

287 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 286 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.

288 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 287 Selection Sort 0123456012345601234560123456 …

289 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 288 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.

290 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 289 Insertion Sort 012345601234560123456 … 01234560123456 0123456

291 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 290 Linear Search -79-5283-4 0123456 current Target is -5

292 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 291 Linear Search -79-5283-4 0123456 current Target is -5

293 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 292 Linear Search -79-5283-4 0123456 Target is -5 current

294 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 293 Linear Search -79-5283-4 0123456 current Numbers can be in any order. Works for Linked Lists.

295 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 294 Binary Search mid target Lower Part

296 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 295 Binary Search mid target Upper Part

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

298 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 297 Binary Search 23581015 0123456 mid highlow target

299 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 298 Binary Search 23581015 0123456 mid highlow target

300 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 299 Binary Search 23581015 0123456 high mid low target

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

302 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 301 Growth Rates / Complexity Constant Logarithmic Linear n log(n) Quadratic Cubic Exponential O(1) O(log(n)) O(n) O(n log(n)) O(n 2 ) O(n 3 ) O(2 n ) Recall:

303 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 302 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.

304 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 303 /* * 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; } Find where the Maximum is.

305 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 304 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; }

306 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 305 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.

307 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 306 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; }

308 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 307 Linear Search -79-5283-4 0123456 current Numbers can be in any order. Works for Linked Lists.

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

310 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 309 Binary Search mid Need –List to be sorted. –To be able to do random accesses.

311 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 310 Case 1: target < list[mid] lowermidupper target New upper list:

312 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 311 Case 2: list[mid] < target lowermidupper target New lower list:

313 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 312 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; } else { return mid; } return -1; } The section where the target could be found halves in size each time

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

315 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 314 Revision Selection Sort Insertion Sort Linear Search Binary Search

316 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 315 Overview Unary Recursion Binary Recursion Examples Features Stacks Disadvantages Advantages

317 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 316 What is Recursion - Recall A procedure defined in terms of itself Components: –Base case –Recursive definition –Convergence to base case

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

319 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 318 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; }

320 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 319 Unary Recursion Functions calls itself once (at most) Usual format: function RecursiveFunction ( ) { if ( base case ) then return base value else return RecursiveFunction ( ) }

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

322 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 321 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,...

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

324 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 323 Copy List HeadPtr struct LinkedListRec { int count; Node* headPtr; }; typedef struct LinkedListRec List;

325 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 324 #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; }

326 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 325 Node* copyNodes(Node* oldNodePtr) { Node* newNodePtr = NULL: if (oldNodePtr != NULL) { newNodePtr = makeNode(oldNodePtr->value); newNodePtr->nextPtr = copyNodes(oldNodePtr->nextPtr); } return newNodePtr; }

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

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

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

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

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

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

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

334 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 333 Types of Recursion Direct. Indirect. Linear. n-ary (Unary, Binary, Ternary, …)

335 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 334 Stacks Every recursive function can be implemented using a stack and iteration. Every iterative function which uses a stack can be implemented using recursion.

336 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 335 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; } x = 2, n = 5 tmp = 1

337 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; } return tmp; } x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 1

338 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; } return tmp; } x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 1 x = 2, n = 1 tmp = 1

339 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; } return tmp; } x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 1 x = 2, n = 1 tmp = 1 x = 2, n = 0 tmp = 1

340 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; } return tmp; } x = 2, n = 5 tmp = 1 x = 2, n = 2 x = 2, n = 1 tmp = 1 tmp = 1*1*2 = 2

341 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 340 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; } x = 2, n = 5 tmp = 1 x = 2, n = 2 tmp = 2*2 = 4

342 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 341 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; } x = 2, n = 5 tmp = 4*4*2 = 32

343 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 342 module power(x, n) { 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} } Stack n = 5, x = 2

344 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 343 module power(x, n) { 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} } 5 Stack n = 5, x = 2

345 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 344 module power(x, n) { 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} } 5 2 Stack n = 2, x = 2

346 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 345 module power(x, n) { 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} } 5 2 1 Stack n = 1, x = 2

347 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 346 module power(x, n) { 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} } 5 2 1 Stack n = 0, x = 2 tmp = 1

348 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 347 module power(x, n) { 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} } 5 2 Stack n = 0, x = 2 tmp = 2

349 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 348 module power(x, n) { 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} } 5 Stack n = 0, x = 2 tmp = 4

350 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 349 module power(x, n) { 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} } Stack n = 0, x = 2 tmp = 32

351 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 350 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; }

352 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 351 Disadvantages May run slower. –Compilers –Inefficient Code May use more space.

353 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 352 Advantages More natural. Easier to prove correct. Easier to analysis. More flexible.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

368 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 367 Revision Recursion

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

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

371 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 370 Parts of a Tree

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

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

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

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

376 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 375 Parts of a Tree root node

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

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

379 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 378 Parts of a Tree sub-tree

380 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 379 Parts of a Tree sub-tree

381 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 380 Parts of a Tree sub-tree

382 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 381 Binary Tree Each node can have at most 2 children

383 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 382 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.

384 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 383 Preorder Traversal Visit the node. Traverse the left subtree. Traverse the right subtree.

385 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 384 Example: Preorder 31 43 64 20 4056 28334759 89 43 31 20 28 40 33 64 56 4759 89

386 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 385 Inorder Traversal Traverse the left subtree. Visit the node. Traverse the right subtree.

387 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 386 Example: Inorder 31 43 64 20 4056 28334759 89 20 31 28 40 33 43 56 4759 64 89

388 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 387 Postorder Traversal Traverse the left subtree. Traverse the right subtree. Visit the node.

389 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 388 Example: Postorder 31 43 64 20 4056 28334759 89 20 28 40 31 33 56 4759 64 89 43

390 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 389 Expression Tree A Binary Tree built with operands and operators. Also known as a parse tree. Used in compilers.

391 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 390 Example: Expression Tree / + / 1 3* 67 4 1/3 + 6*7 / 4

392 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 391 Notation Preorder –Prefix Notation Inorder –Infix Notation Postorder –Postfix Notation

393 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 392 Example: Infix / + / 1 3* 67 4 1 / 3 + * 67 / 4

394 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 393 7 / / / 1 + / 3* 6 4 Example: Postfix Recall: Reverse Polish Notation 1 13 3 6 6 7 7 * * 4 4 / / + +

395 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 394 / + / 1 3* 67 4 Example: Prefix +/13/*674

396 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 395 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.

397 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 396 Example 1: 31 43 64 20 4056 28334759 89 key is an integer

398 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 397 Example 1: 31 43 64 20 4056 28334759 89 key is an integer

399 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 398 Insert Create new node for the item. Find a parent node. Attach new node as a leaf.

400 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 399 Insert 31 43 64 20 4056 28334759 89 Example: 57

401 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 400 Insert 31 43 64 20 4056 28334759 89 Example: 57

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

403 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 402 Search 31 43 64 20 4056 28334759 89 Example: 59 57 found

404 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 403 Search 31 43 64 20 4056 28334759 89 Example: 61 57 failed

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

406 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 405 Overview Binary Search Trees. Hash Tables.

407 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 406 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.

408 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 407 Example 1: 31 43 64 20 4056 28334759 89 key is an integer

409 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 408 Fred Dan Mary Alan Eve BillEric Kate GregLen Sue Example 2: key is a string

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

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

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

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

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

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

416 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 415

417 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 416 struct BookRec { char* author; char* title; char* publisher; /* etc.: other book information. */ }; typedef struct BookRec Book; Book Record key

418 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 417 struct TreeNodeRec { Book info; struct TreeNodeRec* leftPtr; struct TreeNodeRec* rightPtr; }; typedef struct TreeNodeRec TreeNode; Example 4: Binary Search Tree Node

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

420 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 419 #ifndef TREE _ H #define TREE _ H struct TreeNodeRec { float key; struct TreeNodeRec* leftPtr; struct TreeNodeRec* 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

421 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 420 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

422 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 421 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; }

423 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 422 0x2000 newNodePtr NULL 0x2000 newNodePtr 0x2000 newNodePtr 3.3 NULL value 3.3

424 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) { } initially, pointer to root node

425 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) { traverse left sub-tree visit the node traverse right sub-tree }

426 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) { printInorder(nodePtr->leftPtr); printf(“ %f, nodePtr->key); printInorder(nodePtr->rightPtr); }

427 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 426 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); }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

452 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 451 Search 31 43 64 20 4056 28334759 89 Example: 59 57 found

453 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 452 Search 31 43 64 20 4056 28334759 89 Example: 61 57 failed

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

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

456 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 455 /* …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… */ Function Call to Search

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

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

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

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

461 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 460Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } 1.0 1.81.1 2.71.4 1.9 0.40.7 0.8 0.3 0.6 Find 0.5 nodePtr

462 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 461Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } 1.0 1.81.1 2.71.4 1.9 0.40.7 0.8 0.3 0.6 Find 0.5 nodePtr

463 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 462Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } 1.0 1.81.1 2.71.4 1.9 0.40.7 0.8 0.3 0.6 Find 0.5 nodePtr

464 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 463Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } 1.0 1.81.1 2.71.4 1.9 0.40.7 0.8 0.3 0.6 Find 0.5 nodePtr

465 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 464Search TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr; } 1.0 1.81.1 2.71.4 1.9 0.40.7 0.8 0.3 0.6 Find 0.5 nodePtr

466 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 465 Insert 31 43 64 20 4056 28334759 89 Example: 57

467 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 466 Insert 31 43 64 20 4056 28334759 89 Example: 57

468 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 467 Insert Create new node for the item. Find a parent node. Attach new node as a leaf.

469 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 468 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 item’s key is less (greater) than current node’s key: –otherwise, let the left (right) child node be the current node, setting the parent left (right) link equal that node, and repeat recursively.

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

471 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 470 /* …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… */ Function Call to Insert

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

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

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

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

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

477 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 476 Sorting To sort a sequence of items: Insert items into a Binary Search Tree. Then Inorder Traverse the tree.

478 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 477 Sorting: Analysis Insert (i+1) th item: ~ log 2 (i) comparisons ~ log 2 n Average Case: O(n log(n))

479 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 478Sort Sort the following list into a binary search tree 0.51.00.72.12.53.6

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

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

482 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 481Sort 0.51.00.7 2.1 2.53.6 1.0 2.50.5 Sort the following list into a binary search tree

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

484 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 483Sort 1.0 2.50.5 0.73.6 Sort the following list into a binary search tree 0.51.00.72.12.53.6

485 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 484Sort 0.51.00.72.12.53.6 1.0 2.50.5 0.73.62.1 Sort the following list into a binary search tree

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

487 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 486 Revision Binary Search Tree Make Tree Node, Insert item, Search for an item, and Print Inorder. Tree sort.

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

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

490 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 489 Sort Divide and Conquer SortSort SortSortSortSort

491 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 490 Divide and Conquer Combine CombineCombine

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

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

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

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

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

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

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

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

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

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

502 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 501 Merge Sort array:

503 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 502 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); }

504 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 503 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]; }

505 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 504mergeArrays 3515283061014224350 a:b: aSize: 5 bSize: 6 Example:tmp:

506 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 505mergeArrays 51528301014224350 a:b: Example: tmp: i=0 k=0 j=0 36

507 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 506mergeArrays 51528301014224350 a:b: Example: tmp: i=0 k=0 3 j=0 36

508 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 507mergeArrays 31528301014224350 a:b: Example: tmp: i=1j=0 k=1 35 56

509 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 508mergeArrays 3528301014224350 a:b: Example: 35 tmp: i=2j=0 k=2 6 156

510 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 509mergeArrays 352830614224350 a:b: Example: 356 tmp: i=2j=1 k=3 1510

511 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 510 10mergeArrays 3528306224350 a:b: Example: 356 tmp: i=2j=2 k=4 151014

512 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 511 1410mergeArrays 3528306144350 a:b: Example: 356 tmp: i=2j=3 k=5 151022 15

513 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 512 1410mergeArrays 35306144350 a:b: Example: 356 tmp: i=3j=3 k=6 151022 15 28

514 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 513 1410mergeArrays 353061450 a:b: Example: 356 tmp: i=3j=4 k=7 151022 2815 2843 22

515 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 514 1410mergeArrays 3561450 a:b: Example: 356 tmp: i=4j=4 k=8 151022 3015 2843 22 30 28

516 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 515 1410mergeArrays 3561450 a:b: Example: 35630 tmp: i=5j=4 k=9 151022 15 2843 22 30 284350 Done.

517 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 516 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++; }

518 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 517 Merge Sort and Linked Lists Sort Merge

519 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 518 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.

520 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 519 Quick Sort x < ppp <= xPartition Sort

521 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 520 Quick Sort Example: 589351024153713201770 array: size: 11

522 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 521 Quick Sort Example: 58935142415371320770 array: “pivot element” 15

523 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 522partition: Quick Sort Example: 589351424371320770 array: 15 5893514243713207701571451315353789202470 index: 4

524 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 523 Quick Sort Example: array: 71451315353789202470 index: 4 index (size - index - 1)

525 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 524 Quick Sort Example: index (size - index - 1) array[0] array[index + 1] firstPart : array secondPart : array + index + 1 14513153789202470 735

526 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 525 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); } Quick Sort

527 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 526 Partition: Checklist p p 0 p x < pp <= x p x < pp <= xpx < pp <= x

528 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 527Partition Example: 58935142415371320770 array: 15 mid: 4 15893514245371320770 5 0

529 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 528Partition Example: array: k=1 15893514245371320770 0

530 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 529Partition Example: array: k:1 15893514245371320770 index:0 89

531 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 530Partition Example: array: k:2 15893514245371320770 index:0 35

532 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 531Partition Example: array: k:3 15893514245371320770 index:0 14

533 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 532Partition Example: array: k:3 15893514245371320770index:1 8914

534 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 533Partition Example: array: k:4 15143589245371320770index:1 24

535 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 534Partition Example: array: k:5 15143589245371320770index:1 5

536 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 535Partition Example: array: k:5 15143589245371320770index:2 535

537 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 536Partition Example: array: k:6 15148924371320770index:2 53537

538 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 537Partition Example: array: k:7 15148924371320770index:2 535 etc...

539 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 538Partition Example: array: k:11 15141373789202470index:4 535

540 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 539Partition Example: array: 15141373789202470index:4 535

541 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 540Partition Example: array: 15141373789202470index:4 535 157 x < 15 15 <= x

542 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 541 Example: array: 15141373789202470535 157 x < 15 15 <= x pivot now in correct position

543 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 542 Example: 141337892024705357 141357378920247035 15 Sort

544 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 543 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; }

545 copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE 544 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(n 2 ) time.

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


Download ppt "1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M."

Similar presentations


Ads by Google