1 lectures on data structures and c 3ed cs(csi33) by, chandrashekar a.m

545
copy right (version1.0) SUNITHA C.N,CS&E dept,SJ CE 1 Lectures on Lectures on data structures and data structures and C C 3ed CS(CSI33) 3ed CS(CSI33) By, By, CHANDRASHEKAR A.M. CHANDRASHEKAR A.M.

Upload: kerry-gregory

Post on 18-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

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

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

1

Lectures on Lectures on data structures anddata structures and C C

3ed CS(CSI33)3ed CS(CSI33)By,By,

CHANDRASHEKAR A.M.CHANDRASHEKAR A.M.

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

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

2

Data Structures and AlgorithmsData Structures and Algorithms

• Programs.

• Different problems.

• Operations.

• Size of data.

• Resources available.

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

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

3

Overview of LectureOverview of Lecture

• Basic data structures.

• How to manipulate them.

• How to implement them.

• Other algorithms and how to implement them.

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

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

4

This Lecture - ReviewThis Lecture - Review

• Basic C data types

• Boolean

• 1D and multidimensional arrays

• Strings

• Input/Output

• File I/O• Structures and typedef

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

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

5

Basic Data types in CBasic Data types in C

• int

• char

• float

• double

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

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

6

BooleanBoolean

• Has two values, true and false.• In C we use integers as Booleans.• Zero represents false.• Any non-zero integer represents true.• The library <stdbool.h> 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

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

#include <stdbool.h>

bool leapYear(int year){ if ((year % 4 == 0 && year % 100 != 0)

|| (year % 400 == 0) ) { return true; } else { return false; }}

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

#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

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

#include <stdbool.h>

bool leapYear(int year){ if ((year % 4 == 0 && year % 100 != 0)

|| (year % 400 == 0) ) { return true; } else { return false; }}

File inclusion header

Recall:

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

#include <stdbool.h>

bool leapYear(int year){ if ((year % 4 == 0 && year % 100 != 0)

|| (year % 400 == 0) ) { return true; } else { return false; }}

Function definitionRecall:

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

Function name#include <stdbool.h>

bool leapYear(int year){ if ((year % 4 == 0 && year % 100 != 0)

|| (year % 400 == 0) ) { return true; } else { return false; }}

Recall:

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

Must be compatible with the function’s return type

Function return type

#include <stbool.h>

bool leapYear(int year){ if ((year % 4 == 0 && year % 100 != 0)

|| (year % 400 == 0) ) { return true; } else { return true; }}

Recall:

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

#include <stdbool.h>

bool leapYear(int year){ if ((year % 4 == 0 && year % 100 != 0)

|| (year % 400 == 0) ) { return true; } else { return false; }}

Parameter type

Function parameter

Recall:

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

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

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

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

15

Review - Arrays (1D)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:

0 1 N - 1

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

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

16

Review - Multidimensional ArraysReview - Multidimensional Arrays

• Arrays of arrays.

• All the elements are of the same type.

• An element: array2D[row][column]

array2D:

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

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

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

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

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

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

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

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

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

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/OutputReview – Input/Output

Conversion specifiers Pointers to variables where input will be stored

Variables containing data to be printed

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

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/OutputReview – Input/Output

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

#include <stdio.h>

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

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

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 - StringsReview - Strings

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

#include <stdio.h>#include <string.h>

#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

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

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

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

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

27

Review -File Handling in CReview -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().

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

#include <stdio.h>#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; }

Moder : read

w : writea : append

Associate a file handler for every file to be used.

fopen() returns NULL if an error

occurs

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

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

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

#include <stdio.h>#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?

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

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

31

Review -Review - struct struct

• Members may have different types.

structname.membername• structs are also known as “records,” and

members as “fields”

structname:

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

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

32

Review -Review - typedef typedef

• Gives a new name to a type that has already been defined.

• E.g.

typedef struct StudentRec Student;

• Saves typing struct whatever everywhere.

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

#include <stdio.h>

#define MAXNAME 80

struct StudentRec{ char name[MAXNAME]; int mark;};

typedef struct StudentRec Student;

Example :

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

Recall:

Macro substitution

#include <stdio.h>

#define MAXNAME 80

struct StudentRec{ char name[MAXNAME]; int mark;};

typedef struct StudentRec Student;

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

#include <stdio.h>

#define MAXNAME 80

struct StudentRec{ char name[MAXNAME]; int mark;};

typedef struct StudentRec Student;

Recall:

Structure declaration

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

Structure name / tag

Members

Don’t forget this!

Recall:

#include <stdio.h>

#define MAXNAME 80

struct StudentRec{ char name[MAXNAME]; int mark;};

typedef struct StudentRec Student;

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

Recall:

Data type

New type name

#include <stdio.h>

#define MAXNAME 80

struct StudentRec{ char name[MAXNAME]; int mark;};

typedef struct StudentRec Student;

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

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

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

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

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

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

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

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

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

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

42

RevisionRevision• Basic Data Types and booleans• I/O and File I/O• Arrays and Structs• Strings• Typedef

PreparationPreparationNext lecture: Pointers

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

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

43

OverviewOverview

• Revision of Pointers

• Basic Pointer Arithmetic

• Pointers and Arrays

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

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

44

PointersPointers

• 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

10x2000

0x9060

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

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

45

Pointer OperationsPointer 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;

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

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

46

Pointers and Function ArgumentsPointers and Function Arguments

x: 1

y: 2swap

x: 2

y: 1

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

#include <stdio.h>

voidfakeSwap(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

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

#include <stdio.h>

voidfakeSwap(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

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

#include <stdio.h>

voidfakeSwap(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

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

#include <stdio.h>

voidfakeSwap(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:

1tmp:

Solution 1

0x2000

0x2010

0x2060

0x2038

0x2040

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

#include <stdio.h>

voidfakeSwap(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:

1tmp:

Solution 1

0x2000

0x2010

0x2060

0x2038

0x2040

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

#include <stdio.h>

voidfakeSwap(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:

1tmp:

Solution 1

0x2000

0x2010

0x2060

0x2038

0x2040

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

#include <stdio.h>

voidfakeSwap(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

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

#include <stdio.h>

voidtrueSwap(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

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

#include <stdio.h>

voidtrueSwap(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

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

#include <stdio.h>

voidtrueSwap(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

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

#include <stdio.h>

voidtrueSwap(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:

1tmp:

Solution 2

0x2000

0x2010

0x2060

0x2038

0x2040

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

#include <stdio.h>

voidtrueSwap(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:

1tmp:

Solution 2

0x2000

0x2010

0x2060

0x2038

0x2040

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

#include <stdio.h>

voidtrueSwap(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:

1tmp:

Solution 2

0x2000

0x2010

0x2060

0x2038

0x2040

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

#include <stdio.h>

voidtrueSwap(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

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

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

61

More on PointersMore 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);

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

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

62

struct DataBaseRec{

};

typedef struct DataBaseRec DataBase;

/* Very Large Structure */

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

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

63

DataBasereadNewEntry(DataBase theDataBase){

return theDataBase;}

voidprintDataBase(DataBase theDataBase){

}

/* Some code */

/* Some more code */

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

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

64

voidreadNewEntry(DataBase* dataBasePtr){

}

voidprintDataBase(const DataBase* dataBasePtr){

}

/* Some code */

/* Some more code */

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

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

65

voidreadNewEntry(DataBase* dataBasePtr){

}

voidprintDataBase(const DataBase* dataBasePtr){

}

/* Some code */

/* Some more code */

(DataBase*

Address of Database

Database*

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

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

66

voidreadNewEntry(DataBase* dataBasePtr){

}

voidprintDataBase(const DataBase* dataBasePtr){

}

/* Some code */

/* Some more code */

Database cannot change in this function.

const

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

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?

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

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

68

Pointers and FunctionsPointers 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.

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

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

69

Pointers and ArraysPointers 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;

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

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

70

Pointers and Arrays (cont)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:

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

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

71

float array[5];

float* pPtr = array;

float* qPtr = NULL;

0x2008

0x2008

0x2004

array:

pPtr:

0x2008 0x200C 0x2010 0x2014 0x2018

0 1 2 3 4

NULL0x2000

qPtr:

Basic Pointer ArithmeticBasic Pointer Arithmetic

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

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:

0x2008 0x200C 0x2010 0x2014 0x2018

0 1 2 3 4

NULL0x2000

qPtr:

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

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:

0x2008 0x200C 0x2010 0x2014 0x2018

0 1 2 3 4

NULL0x2000

qPtr:

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

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:

0x2008 0x200C 0x2010 0x2014 0x2018

0 1 2 3 4

0x20100x2000

qPtr:

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

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:

0x2008 0x200C 0x2010 0x2014 0x2018

0 1 2 3 4

0x20100x2000

qPtr:

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

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

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

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

77

RevisionRevision

• 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

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

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

78

Next LectureNext Lecture• Stacks

– abstract data type– main operations– implementation

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

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

79

Basic Data StructuresBasic Data Structures

• Stacks

• Queues

• Lists

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

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

80

Overview of StacksOverview of Stacks

• What is a Stack?

• Operations on a Stack– push, pop– initialize– status: empty, full

• Implementation of a Stack.

• Example: Reversing a sequence.

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

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

81

A StackA Stack

Top

Items on the Stack

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

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

82

PushPush

Top

After

Top

Before

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

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

83

PopPop

Top

Before After

Top

This comes off the stack

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

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

84

OperationsOperations

• 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

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

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

85

Stack PropertiesStack 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.

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

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

86

ImplementationImplementation

Top

index0

1

2

:

array(upside-down)

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

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

87

ImplementationImplementation

Top

float entry[MAXSTACK];

int top;0

1

2

:

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

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

88

#ifndef STACK.H#define STACK.H#include <stdbool.h>#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

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

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:

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

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

90

#include <stdio.h>#include <stdlib.h>#include “stack.h”

void initializeStack(Stack* stackPtr){ stackPtr -> top = -1;}

top:

.

.

.

entry:

Stack:

addr of Stack

stackPtr:

-1

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

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

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

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

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

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

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

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

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

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

95

#include <stdio.h>#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”);}

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

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

96

RevisionRevision• Stack

• Operations on a Stack– push, pop– initialize– status: empty, full– others: clear, size

• Implementation.

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

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

97

Next LectureNext Lecture

• Queue

• Main Operations

• Implementation

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

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

98

Basic Data StructuresBasic Data Structures

• Stacks

• Queues

• Lists

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

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

99

OverviewOverview

• What is a Queue?

• Queue Operations.

• Applications.

• Linear Implementation.

• Circular Implementation.

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

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

100

InsertInsertBefore

Front RearAfter

Front Rear

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

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

101

DeleteDeleteBefore

Front Rear

After

Front RearThis comes off the queue

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

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

102

OperationsOperations

• 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?

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

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

103

ApplicationsApplications

• In operating systems, e.g. printer queues, process queues, etc.

• Simulation programs.

• Algorithms.

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

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

104

Linear ImplementationLinear Implementation

Front Rear

0 1 2 3 4 5 6 7

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

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

105

InsertInsert

Front Rear

0 1 2 3 4 5 6 7

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

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

106

InsertInsert

Front Rear

0 1 2 3 4 5 6 7

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

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

107

DeleteDelete

Front Rear

0 1 2 3 4 5 6 7

This comes off the queue

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

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

108

DeleteDelete

Front Rear

0 1 2 3 4 5 6 7

This comes off the queue

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

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

109

InsertInsert

Front Rear

0 1 2 3 4 5 6 7

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

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

110

InsertInsert

Front Rear

0 1 2 3 4 5 6 7

NO SPACE

HERE

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

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

111

InsertInsert

Front Rear

0 1 2 3 4 5 6 7

SPACE HERE

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

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

112

Circular ImplementationCircular Implementation07

1

2

34

5

6

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

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

113

Circular ImplementationCircular Implementation

Front Rear

0 1 2 3 4 5 6 7

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

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

114

InsertInsert

FrontRear

0 1 2 3 4 5 6 7

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

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

115

#ifndef QUEUE.H#define QUEUE.H#include <stdbool.h>#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

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

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:

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

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

117

#include <stdio.h>#include <stdlib.h>#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

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

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

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

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

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

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

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

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

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

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

122

RevisionRevision

• Queue

• Main Operations

• Implementation.

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

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

123

Basic Data TypesBasic Data Types

StackLast-In, First-Out (LIFO)initialize, push, pop, status

QueueFirst-In, First-Out (FIFO)initialize, Insert, delete, status

• List

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

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

124

OverviewOverview

• Lists.

• Operations.

• Abstract Data Types (ADT).

• Programming Styles.

• Implementations of Lists.

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

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

125

ListsLists

SEALFOXDEERAPE EMU0 1 3 42

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

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

126

InsertionInsertion

SEALFOXDEERAPE0 1 32

EMU Inserted at position 2

SEALFOXDEERAPE0 1 3 4

EMU2

Before:

After:

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

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

127

DeletionDeletion

SEALFOXDEERAPE0 1 3 4

EMU2

Delete item at position 3

SEALDEERAPE0 1 3

EMU2

Before:

After:

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

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

128

List OperationsList 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.

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

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

129

A List ADTA 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:

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

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

130

Abstract Data Type (ADT)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.

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

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

131

A Stack ADTA 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:

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

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

132

A Queue ADTA 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:

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

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

133

ComparisonComparison

• 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.

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

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

134

A Rational Number ADTA 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:

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

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

135

A String ADTA 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:

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

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

136

Simple List ImplementationSimple List Implementation

0 1 2 3 4 5

APE DEER FOX SEAL

EMU

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

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

137

Simple List ImplementationSimple List Implementation

0 1 2 3 4 5

APE DEER FOX SEAL

EMU

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

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

138

Simple List ImplementationSimple List Implementation

0 1 2 3 4 5

APE DEER FOX SEALEMU

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

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

139

Linked List Implementation:Linked List Implementation:Using Array IndexUsing Array Index

DEER FOX APE SEAL

0 1 2 3 4 5

1 3 0 -1

data

marks last item

start

link to next item

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

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

140

Linked List Implementation:Linked List Implementation:Using Array IndexUsing Array Index

DEER FOX APE SEAL

0 1 2 3 4 5

3 0 -1

startinsert: EMU

EMU

11

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

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

141

Linked List Implementation:Linked List Implementation:Using Array IndexUsing Array Index

DEER FOX APE SEAL

0 1 2 3 4 5

4 3 0 -1

startinsert: EMU

EMU

1

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

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

142

Linked List Implementation:Linked List Implementation:Using PointersUsing Pointers

DEER FOX APE SEAL

0x2000 0x2008 0x2010 0x2018 0x2020 0x2018

0x2020 0x2018 0x2000 NULL

start

EMU

0x2008

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

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

143

Linked List Implementation:Linked List Implementation:Using PointersUsing Pointers

DEER FOX APE SEAL

0x2000 0x2008 0x2010 0x2018 0x2020 0x2018

0x2020 0x2018 0x2000 NULL

start

EMU

0x2008

special pointerconstant

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

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

144

RevisionRevision

• List– initialize, insert, delete, position, status– implementations

• Difference between Stacks, Queues, and Lists.

• ADT.

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

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

145

OverviewOverview

• Linked Stack.– Push– Pop

• Linked Queue.– Insert– Delete

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

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

146

Linked StackLinked Stack

Top of the Stack

NULL pointer

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

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

147

#ifndef LINKEDSTACKH#define LINKEDSTACKH#include <stdbool.h>#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

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

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

Initialize StackInitialize Stack

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

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

149

PushPush

Top

Top

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

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

150

PushPush

• create a new node for the item

• link the new node to the current top node

• make the new node the new top

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

void push(Stack* stackPtr, float item){ Node* newNodePtr = makeNode(item);

newNodePtr->nextPtr = stackPtr->topPtr; stackPtr->topPtr = newNodePtr;}

PushPush

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

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

152

PopPopTop

Top

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

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

153

PopPop

• 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

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

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

PopPop

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

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

155

Linked QueueLinked Queue

Front Rear

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

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

156

#ifndef LINKEDQUEUEH#define LINKEDQUEUEH#include <stdbool.h>#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

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

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

Initialize QueueInitialize Queue

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

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

158

InsertInsert

Front Rear

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

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

159

InsertInsert

Front Rear

Front Rear

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

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

160

InsertInsert• 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

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

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

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

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

162

DeleteDelete

Front Rear

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

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

163

DeleteDelete

Front Rear

RearFront

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

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

164

DeleteDelete

• 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

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

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

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

#include <stdio.h>#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); }}

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

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

167

RevisionRevision

• Linked Stack.– Initialize, Pop, Push.

• Linked Queue.– Initialize, Insert,Delete

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

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

168

OverviewOverview

• What is Dynamic Memory ?

• How to find the size of objects.

• Allocating memory.

• Deallocating memory.

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

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

169

Virtual MemoryVirtual Memory

Text Segment

Data Segment

Stack segment

program instructions

static and dynamic data

local variables, parameters

free memory

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

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

170

Virtual MemoryVirtual Memory

Text Segment

Static data

Heap

Stack segment

global variables, etc.

dynamic data

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

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

171

Virtual MemoryVirtual Memory

Text Segment

Static data

Heap

Stack segment

memory is allocated and deallocated as needed

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

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

172

What is Dynamic Memory?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

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

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

173

Example: Run-Time StackExample: 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.

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

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

174

#include <stdio.h>

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:

stackstack

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

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

175

#include <stdio.h>

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.15a

b

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

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

176

#include <stdio.h>

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.15a

b

3.15x

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

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

177

#include <stdio.h>

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.15a

b

3.15x

line 16

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

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

178

#include <stdio.h>

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.15a

b

3.15x

line 16

result

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

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

179

#include <stdio.h>

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.15a

b

3.15x

line 16

9.9225result

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

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

180

#include <stdio.h>

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.15a

b

3.15x

line 16

9.9225result

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

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

181

#include <stdio.h>

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.15a

b

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

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

182

#include <stdio.h>

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.15a

b

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

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

183

#include <stdio.h>

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:

stackstack

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

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

184

#include <stdlib.h>#include <stdio.h>

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

}

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

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

185

How much memory to allocate?How much memory to allocate?

•The sizeof operator returns the size of an object, or type, in bytes.

•Usage:

sizeof(Type)

sizeof Object

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

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;

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

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

187

Notes on Notes on sizeofsizeof

•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;

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

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

188

#include <stdio.h>

#define MAXNAME 80#define MAXCLASS 100

struct StudentRec{ char name[MAXNAME]; float mark;};

typedef struct StudentRec Student;

Example 2:

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

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.):

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

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

190

Notes on Notes on sizeof sizeof (cont.)(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)

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

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

191

Dynamic Memory: HeapDynamic 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)

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

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

192

#include <stdlib.h>

main(){ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5;

free(aPtr);}

Example 1:

NULL

stack

aPtr

heap

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

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

193

#include <stdlib.h>

main(){ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5;

free(aPtr);}

heap

0x3a04

NULL

stack

aPtr 0x3a04

Example 1:

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

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

194

#include <stdlib.h>

main(){ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5;

free(aPtr);}

heap

0x3a04

NULL

stack

aPtr 0x3a04

“type cast”

Example 1:

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

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

195

#include <stdlib.h>

main(){ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5;

free(aPtr);}

5

heap

0x3a04

stack

aPtr 0x3a04

Example 1:

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

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

196

#include <stdlib.h>

main(){ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5;

free(aPtr);}

0x3a04

stack

aPtr

Example 1:

heap

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

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

197

#include <stdlib.h>

main(){ int* aPtr = NULL; aPtr = (int*)malloc(sizeof(int)); *aPtr = 5;

free(aPtr);}

0x3a04

stack

aPtr

Example 1:

deallocates memory

heap

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

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

198

#include <stdlib.h>

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:

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

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

199

Allocating MemoryAllocating 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.

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

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

200

Deallocating MemoryDeallocating 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.

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

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:

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

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:

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

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

203

Common ErrorsCommon 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.

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

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

204

#include <stdio.h>#include <stdlib.h>

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:

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

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

205

RevisionRevision

• sizeof

• malloc

• free

• Common errors.

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

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

206

Overview of TopicOverview of Topic

• Review List Implementations.

• Nodes.

• Linked Stacks.

• Linked Queues

• Linked Lists.

• Other List Operations

Today’s Lecture

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

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

207

ListsLists

151031 60 1 3 42

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

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

208

A List ADTA 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:

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

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

209

InsertionInsertion

1510310 1 32

6 Inserted at position 2

1510310 1 3 4

62

Before:

After:

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

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

210

A List ADTA 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

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

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

211

Simple List ImplementationSimple List Implementation

1 3 10 15 21

6

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

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

212

Expansion and InsertionExpansion and Insertion

1 3 10 15 21

1 3 10 15 21

6

6

Copy old array, leave space for the new value

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

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

213

DisadvantagesDisadvantages

• Lots of memory needs to be allocated.

• Lots of copying needs to be done.

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

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

214

Linked List Implementation:Linked List Implementation:Using PointersUsing Pointers

3 15 1 21

0x2000 0x2008 0x2010 0x2018 0x2020

0x2020 0x2018 0x2000 NULL

start

10

0x2008

insert: 6

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

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

215

Method 1Method 1 start

3 15 1 21

0x2000 0x2008 0x2010 0x2018 0x2020

0x2020 0x2018 0x2000 NULL

10

0x2008

0x30F0 0x30F8 0x3100 0x3108 0x3110

newStart

0x3118

insert: 6

1 3

0x30F8 0x3100 0x3108 0x3110 0x3118 NULL

6 10 15 21

0x30F0

Copy old array, leave space for the new value

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

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

216

Method 2Method 2

3 15 1 21

0x2000 0x2008 0x2010 0x2018 0x2020

0x2020 0x2018 0x2000 NULL

start

10

0x2008

insert: 6

6newItem

0x30F0

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

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

217

Method 2Method 2

3 15 1 21

0x2000 0x2008 0x2010 0x2018 0x2020

0x30F0 0x2018 0x2000 NULL

start

10

0x2008

insert: 6

6newItem

0x30F0

0x2020

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

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

218

AdvantagesAdvantages

• Only a little amount of memory needs to be allocated.

• Only a little amount of copying needs to be done.

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

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:

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

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

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

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

221

Make NodeMake 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

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

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

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

#include <stdio.h>#include <stdlib.h>#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; } }}

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

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

224

0x30F0 0x2124 6firstNodePtr: lastNodePtr: item:

0x30F0

0x2124

0x2A40

1

0x2A40nextPtr:

value:

6

NULLnextPtr:

value:

3

0x2124nextPtr:

value:

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

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

225

Linked StructureLinked Structure

10x30F0

6

3 0x2124

0x2124

0x2A40

NULL

0x2A40 0x30F0firstNodePtr:

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

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

226

Linked StructureLinked Structure

10x30F0

3 0x21240x2A40

0x2A40 0x30F0firstNodePtr:

60x2124 NULL

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

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

227

Linked StructureLinked Structure

1

3

firstNodePtr:

6

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

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

228

Linked StructureLinked Structure

firstNodePtr:

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

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

229

RevisionRevision

• Node

• How to make a new Node

• Linked Structure

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

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

230

OverviewOverview

• Operations for Lists.

• Implementation of Linked Lists.

• Double Linked Lists.

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

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

231

List OperationsList 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.

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

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

232

ComparsionComparsion

Linked Storage– Unknown list size.– Flexibility is needed.

Contiguous Storage– Known list size.– Few insertions and deletions are made within the list.– Random access

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

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

233

Linked ListLinked List

Head

0 1 2 3

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

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

234

#ifndef LINKEDLISTH#define LINKEDLISTH#include <stdbool.h>#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

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

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

235

void initializeList(List* listPtr){ listPtr->headPtr = NULL; listPtr->count = 0;}

Initialize ListInitialize List

count

headPtr

0

NULL

listPtr addr of list

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

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

236

Set PositionSet 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

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

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

237

Set PositionSet Position

Head

0 21

2 position

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

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 < 0 || position >= listPtr->count) { fprintf(stderr, “Invalid position\n”); exit(1); } else { for (i = 0; i < position; i++) { nodePtr = nodePtr->nextPtr; } }

return nodePtr;}

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

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

239

Set PositionSet Position

Head

2 position

0x4000

0 i

NodePtr

0x30a80x20300x4000

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

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

240

Set PositionSet Position

Head

2 position

0x4000

0 i

NodePtr

0x30a80x20300x4000

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

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

241

Set PositionSet Position

Head

2 position

0x2030

1 i

NodePtr

0x30a80x20300x4000

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

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

242

Set PositionSet Position

Head

2 position

0x30a8

2 i

NodePtr

0x30a80x20300x4000

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

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

243

InsertInsert

Head

0 21

If we insert it at position 0.

Head

10 2

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

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

244

InsertInsert

Head

0 21

If we insert it at position 0.

0 21 3

Head

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

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

245

Instead, suppose we insert it at position 1.

Head

0 21

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

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

246

Head

Instead, suppose we insert it at position 1.

0 32

1

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

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

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

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

248

Inserting – New ListInserting – New List

Head

0 position

0x30a8

NULL

newNodePtr

0x30a8

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

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

249

Inserting – New ListInserting – New List

Head

0 position

0x30a8 newNodePtr

0x30a8

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

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

250

Inserting – Start of ListInserting – Start of List

HeadHead0x30a80x2008

0x2000

0position

0x2000newNodePtr

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

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

251

Inserting – Start of ListInserting – Start of List

HeadHead0x30a80x2008

0x2000

0position

0x2000newNodePtr

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

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

252

Inserting – Start of ListInserting – Start of List

HeadHead0x30a80x2008

0x2000

0position

0x2000newNodePtr

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

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

253

Inserting – Inside the ListInserting – Inside the List

0x2000

1position

0x2000newNodePtr

Head

0x30500x3080

NodePtr 0x3080

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

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

254

Inserting – Inside the ListInserting – Inside the List

0x2000

1position

0x2000newNodePtr

Head

0x30500x3080

NodePtr 0x3080

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

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

255

Inserting – Inside the ListInserting – Inside the List

0x2000

1position

0x2000newNodePtr

Head

0x30500x3080

NodePtr 0x3080

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

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

256

DeleteDelete

2

Head

310

If we delete the Node at position 0.

Head

210

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

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

257

Head

If we delete the Node at position 2.

2 310

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

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

258

Head

If we delete the Node at position 2.

2 210

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

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 < listPtr->count) { if (position == 0) { oldNodePtr = listPtr->headPtr; listPtr->headPtr = oldNodePtr->nextPtr; } else { nodePtr = setPosition(listPtr, position - 1); oldNodePtr = nodePtr->nextPtr; nodePtr->nextPtr = oldNodePtr->nextPtr; } listPtr->count--; free(oldNodePtr); } else { fprintf(stderr, “List is empty or invalid position.\n”); exit(1); }}

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

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

260

Deleting – 1Deleting – 1stst Node Node

Head

0 position

0x4000 NodePtr

0x30a80x20300x4000

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

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

261

Head0 position

0x4000 NodePtr

0x30a80x20300x4000

Deleting – 1Deleting – 1stst Node Node

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

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

262

Head0 position

0x4000 NodePtr

0x30a80x2030

Deleting – 1Deleting – 1stst Node Node

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

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

263

Deleting – Middle NodeDeleting – Middle Node

Head

1 position

0x2030 OldNodePtr

0x30a80x20300x4000

0x2030 NodePtr

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

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

264

Head

0x30a80x20300x4000

Deleting – Middle NodeDeleting – Middle Node

1 position

0x2030 OldNodePtr

0x2030 NodePtr

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

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

265

Head

0x30a80x4000

Deleting – Middle NodeDeleting – Middle Node

1 position

0x2030 OldNodePtr

0x2030 NodePtr

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

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

266

Double Linked List OperationsDouble Linked List Operations

• Go to a position in the list.

• Insert an item in a position in the list.

• Delete an item from a position in the list.

• Retrieve an item from a position.

• Replace an item at a position.

• Traverse a list, in both directionsin both directions.

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

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

267

Double Linked ListDouble Linked List

Current

0 1 2 3 4

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

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;

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

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

269

Insert at endInsert at end

currentPtrnewPtr

0x4000 0x3080 0x2030 0x2000

0x4000 0x3080

0x3080 0x2030 NULL

NULLNULL

NULL

0x2000prevPtr

0x2030

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

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

270

Insert at endInsert at end

newPtr

0x4000 0x3080 0x2030 0x2000

0x4000 0x3080

0x3080 0x2030 0x2000

NULLNULL

NULL

0x2000prevPtr

0x2030

currentPtr

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

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

271

Insert at endInsert at end

newPtr

0x4000 0x3080 0x2030 0x2000

0x4000 0x3080

0x3080 0x2030 0x2000

NULLNULL

0x2030

0x2000prevPtr

0x2030

currentPtr

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

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

272

Insert inside the listInsert inside the list

newPtr

0x4000 0x3080 0x2030

0x2000

0x4000 0x3080

0x3080 0x2030NULL

NULL

NULL

NULL

0x2000prevPtr

0x3080

currentPtr

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

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

273

Insert inside the listInsert inside the list

newPtr

0x4000 0x3080 0x2030

0x2000

0x4000 0x3080

0x3080 0x2030NULL

NULL

2030

NULL

0x2000prevPtr

0x3080

currentPtr

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

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

274

Insert inside the listInsert inside the list

newPtr

0x4000 0x3080 0x2030

0x2000

0x4000 0x3080

0x3080 0x2030NULL

NULL

2030

3080

0x2000prevPtr

0x3080

currentPtr

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

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

275

Insert inside the listInsert inside the list

newPtr

0x4000 0x3080 0x2030

0x2000

0x4000 0x2000

0x3080 0x2030NULL

NULL

2030

3080

0x2000prevPtr

0x3080

currentPtr

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

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

276

Insert inside the listInsert inside the list

newPtr

0x4000 0x3080 0x2030

0x2000

0x4000 0x2000

0x3080 0x2000NULL

NULL

2030

3080

0x2000prevPtr

0x3080

currentPtr

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

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

277

Delete from endDelete from end

oldPtr

0x4000 0x3080 0x2030

0x4000 0x3080

0x3080 0x2030 NULL

NULL

0x2030currentPtr

prevPtr 0x3080

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

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

278

Delete from endDelete from end

0x4000 0x3080 0x2030

0x4000 0x3080

0x3080 NULL NULL

NULL

oldPtr 0x2030currentPtr

prevPtr 0x3080

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

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

279

Delete from endDelete from end

0x4000 0x3080

0x4000

0x3080 NULL

NULL

oldPtr 0x2030currentPtr

prevPtr 0x3080

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

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

280

Delete from inside listDelete from inside list

0x4000 0x3080 0x2030

0x4000 0x3080

0x3080 0x2030 NULL

NULL

oldPtr 0x3080currentPtr

prevPtr 0x4000

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

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

281

Delete from inside listDelete from inside list

0x4000 0x3080 0x2030

0x4000 0x3080

0x2030 0x2030 NULL

NULL

oldPtr 0x3080currentPtr

prevPtr 0x4000

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

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

282

Delete from inside listDelete from inside list

0x4000 0x3080 0x2030

0x4000 0x4000

0x2030 0x2030 NULL

NULL

oldPtr 0x3080currentPtr

prevPtr 0x4000

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

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

283

Delete from inside listDelete from inside list

Head

0x4000 0x2030

0x4000

0x2030 NULL

NULL

oldPtr 0x3080currentPtr

prevPtr 0x4000

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

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

284

RevisionRevision

• Linked List.

• Benefits of different implementations.

• Double Linked List.

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

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

285

OverviewOverview

• Selection Sort

• Insertion Sort

• Linear Search.

• Binary Search.

• Growth Rates.

• Implementation.

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

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

286

Selection SortSelection 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.

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

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

287

Selection SortSelection Sort

01 2 3 45 6

01 2 345 6

01 23 4 5 6

01 2 3 4 5 6

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

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

288

Insertion SortInsertion 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.

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

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

289

Insertion SortInsertion Sort01 2 3 45 6

01 2 3 45 6

0 1 2 3 45 6

0 1 2 3 45 6

0 1 2 3 45 6

0 1 2 3 45 6

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

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

290

Linear SearchLinear Search

-7 9 -5 2 8 3 -4

0 1 2 3 4 5 6

current

• Target is -5

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

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

291

Linear SearchLinear Search

-7 9 -5 2 8 3 -4

0 1 2 3 4 5 6

current

• Target is -5

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

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

292

Linear SearchLinear Search

-7 9 -5 2 8 3 -4

0 1 2 3 4 5 6

• Target is -5

current

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

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

293

Linear SearchLinear Search

-7 9 -5 2 8 3 -4

0 1 2 3 4 5 6

current

• Numbers can be in any order.

• Works for Linked Lists.

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

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

294

Binary SearchBinary Search

mid

target

Lower Part

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

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

295

Binary SearchBinary Search

mid

target

Upper Part

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

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

296

Binary SearchBinary Search

mid

• Need– List to be sorted.– To be able to do random accesses.

target

Upper Part

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

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

297

Binary SearchBinary Search

-1 2 3 5 8 10 15

0 1 2 3 4 5 6

mid highlow

target

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

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

298

Binary SearchBinary Search

-1 2 3 5 8 10 15

0 1 2 3 4 5 6

mid highlow

target

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

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

299

Binary SearchBinary Search

-1 2 3 5 8 10 15

0 1 2 3 4 5 6

high

mid

low

target

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

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

300

Other Uses of Binary SearchOther Uses of Binary Search

• To find where a function is zero.

• Compute functions.

• Tree data structures.

• Data processing.

• Debugging code.

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

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

301

Growth Rates / ComplexityGrowth Rates / Complexity

• Constant• Logarithmic• Linear• n log(n) • Quadratic• Cubic• Exponential

• O(1)• O(log(n))• O(n)• O(n log(n))• O(n2)• O(n3)• O(2n)

Recall:

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

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

302

Selection SortSelection 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.

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

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.Find where the Maximum is.

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

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

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

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

305

Insertion SortInsertion 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.

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

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

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

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

307

Linear SearchLinear Search

-7 9 -5 2 8 3 -4

0 1 2 3 4 5 6

current

• Numbers can be in any order.

• Works for Linked Lists.

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

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 SearchLinear Search

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

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

309

Binary SearchBinary Search

mid

• Need– List to be sorted.– To be able to do random accesses.

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

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

310

Case 1: target < list[mid]

lower mid upper

target

New upper

list:

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

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

311

Case 2: list[mid] < target

lower mid upper

target

New lower

list:

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

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 wherethe target could be foundhalves in size each time

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

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

313

ComparisonComparisonArray Linked List

Selection Sort

Insertion Sort

Linear Search

Binary Search

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

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

314

RevisionRevision• Selection Sort• Insertion Sort• Linear Search• Binary Search

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

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

315

OverviewOverview

• Unary Recursion

• Binary Recursion

• Examples

• Features

• Stacks

• Disadvantages

• Advantages

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

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

316

What is Recursion - RecallWhat is Recursion - Recall

• A procedure defined in terms of itself

• Components:

– Base case

– Recursive definition

– Convergence to base case

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

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

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

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

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

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

319

Unary RecursionUnary Recursion

• Functions calls itself once (at most)• Usual format:

function RecursiveFunction ( <parameter(s)> ){

if ( base case ) thenreturn base value

elsereturn RecursiveFunction ( <expression> )

}

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

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

320

Unary RecursionUnary 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 )}

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

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

321

Binary RecursionBinary 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,...

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

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

322

Binary RecursionBinary 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 )}

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

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

323

Copy ListCopy ListHeadPtr

struct LinkedListRec{ int count; Node* headPtr;};

typedef struct LinkedListRec List;

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

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

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

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

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

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

326

Copy NodesCopy NodesOldNodePtr

NewNodePtr

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

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

327

Copy NodesCopy NodesOldNodePtr

NewNodePtr

NewNodePtr->next is set to the Result of calling copy nodes onThe remainder of the list

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

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

328

Copy NodesCopy NodesOldNodePtr

NewNodePtrNewNodePtr

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

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

329

Copy NodesCopy NodesOldNodePtr

NewNodePtrNewNodePtr NewNodePtr

NULL

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

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

330

Copy NodesCopy Nodes

NewNodePtr NewNodePtr

OldNodePtr

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

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

331

Copy NodesCopy Nodes

NewNodePtr

OldNodePtr

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

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

332

Recursion ProcessRecursion Process

Every recursive process consists of:

1. A base case. 2. A general method that reduces to the base case.

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

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

333

Types of RecursionTypes of Recursion

• Direct.

• Indirect.

• Linear.

• n-ary (Unary, Binary, Ternary, …)

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

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

334

StacksStacks

• Every recursive function can be implemented using a stack and iteration.

• Every iterative function which uses a stack can be implemented using recursion.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Stackn = 5, x = 2

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

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

Stackn = 5, x = 2

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

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

Stackn = 2, x = 2

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

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

Stackn = 1, x = 2

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

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

Stackn = 0, x = 2

tmp = 1

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

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

Stackn = 0, x = 2

tmp = 2

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

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

Stackn = 0, x = 2

tmp = 4

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

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

Stackn = 0, x = 2

tmp = 32

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

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

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

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

351

DisadvantagesDisadvantages

• May run slower.– Compilers– Inefficient Code

• May use more space.

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

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

352

AdvantagesAdvantages

• More natural.

• Easier to prove correct.

• Easier to analysis.

• More flexible.

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

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

353

Free List – Non RecursiveFree List – Non RecursiveHead

/* Delete the entire list */void FreeList(Node* head){ Node* next;

while (head != NULL) { next=head->next; free(head); head=next; }}

0x2000 0x4c680x258a

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

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

354

Free List – Non RecursiveFree List – Non Recursivehead

/* Delete the entire list */void FreeList(Node* head){ Node* next;

while (head != NULL) { next=head->next; free(head); head=next; }}

next

0x2000 0x258a 0x4c68

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

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

355

Free List – Non RecursiveFree List – Non Recursivehead

/* Delete the entire list */void FreeList(Node* head){ Node* next;

while (head != NULL) { next=head->next; free(head); head=next; }}

next

0x258a 0x4c68

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

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

356

Free List – Non RecursiveFree List – Non Recursivehead

/* Delete the entire list */void FreeList(Node* head){ Node* next;

while (head != NULL) { next=head->next; free(head); head=next; }}

next

NULL

0x4c68

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

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

357

Free List – Non RecursiveFree List – Non Recursivehead

/* 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.

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

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

358

Free ListFree ListHead

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

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

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

359

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x258a 0x4c680x2000

Stack in memory

0x2000

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

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

360

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x258a 0x4c680x2000

0x2000

0x258a

Stack in memory

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

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

361

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x258a 0x4c680x2000

0x2000

0x258a

0x4c68

Stack in memory

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

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

362

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x258a 0x4c680x2000

NULL

0x2000

0x258a

0x4c68

Stack in memory

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

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

363

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x258a 0x4c680x2000

0x2000

0x258a

0x4c68

Stack in memory

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

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

364

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x258a0x2000

0x2000

0x258a

Stack in memory

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

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

365

Free ListFree Listlist

/* Delete the entire list */void FreeList(Node* list){ if (list==NULL) return; FreeList(list->next); free(list);}

0x2000

0x2000

Stack in memory

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

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

366

Free ListFree ListHead

/* 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.

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

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

367

RevisionRevision

• Recursion

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

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

368

OverviewOverview

• Trees.

• Terminology.

• Traversal of Binary Trees.

• Expression Trees.

• Binary Search Trees.

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

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

369

TreesTrees

• Family Trees.

• Organisation Structure Charts.

• Program Design.

• Structure of a chapter in a book.

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

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

370

Parts of a TreeParts of a Tree

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

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

371

Parts of a TreeParts of a Tree

nodes

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

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

372

Parts of a TreeParts of a Treeparent node

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

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

373

Parts of a TreeParts of a Treechild

nodesparent node

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

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

374

Parts of a TreeParts of a Treechild

nodesparent node

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

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

375

Parts of a TreeParts of a Tree

root node

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

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

376

Parts of a TreeParts of a Treeleaf

nodes

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

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

377

Parts of a TreeParts of a Tree

sub-tree

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

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

378

Parts of a TreeParts of a Tree

sub-tree

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

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

379

Parts of a TreeParts of a Tree

sub-tree

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

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

380

Parts of a TreeParts of a Tree

sub-tree

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

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

381

Binary TreeBinary Tree• Each node can have at most 2 children

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

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

382

TraversalTraversal

• 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.

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

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

383

Preorder TraversalPreorder Traversal

• Visit the node.

• Traverse the left subtree.

• Traverse the right subtree.

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

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

384

Example: PreorderExample: Preorder

31

43

64

20 40 56

28 33 47 59

89

43 31 20 28 40 33 64 56 47 59 89

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

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

385

Inorder TraversalInorder Traversal

• Traverse the left subtree.

• Visit the node.

• Traverse the right subtree.

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

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

386

Example: InorderExample: Inorder

31

43

64

20 40 56

28 33 47 59

89

20 3128 4033 43 5647 59 64 89

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

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

387

Postorder TraversalPostorder Traversal

• Traverse the left subtree.

• Traverse the right subtree.

• Visit the node.

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

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

388

Example: PostorderExample: Postorder

31

43

64

20 40 56

28 33 47 59

89

2028 40 3133 5647 59 6489 43

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

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

389

Expression TreeExpression Tree

• A Binary Tree built with operands and operators.

• Also known as a parse tree.

• Used in compilers.

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

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

390

Example: Expression TreeExample: Expression Tree

/

+

/

1 3 *

6 7

4

1/3 + 6*7 / 4

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

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

391

NotationNotation

• Preorder– Prefix Notation

• Inorder– Infix Notation

• Postorder– Postfix Notation

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

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

392

Example: InfixExample: Infix

/

+

/

1 3 *

6 7

4

1 / 3 + *6 7 / 4

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

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

393

7

//

/

1

+

/

3 *

6

4

Example: PostfixExample: Postfix

Recall: Reverse Polish Notation

1

1 3

3

6

6

7

7

*

*

4

4

/

/

+

+

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

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

394

/

+

/

1 3 *

6 7

4

Example: PrefixExample: Prefix

+ / 1 3 / * 6 7 4

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

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

395

Binary Search Tree 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.

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

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

396

Example 1:

31

43

64

20 40 56

28 33 47 59

89

key is an integer

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

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

397

Example 1:

31

43

64

20 40 56

28 33 47 59

89

key is an integer

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

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

398

InsertInsert

• Create new node for the item.

• Find a parent node.

• Attach new node as a leaf.

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

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

399

InsertInsert

31

43

64

20 40 56

28 33 47 59

89

Example:57

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

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

400

InsertInsert

31

43

64

20 40 56

28 33 47 59

89

Example:57

57

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

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

401

Search: ChecklistSearch: 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.

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

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

402

SearchSearch

31

43

64

20 40 56

28 33 47 59

89

Example: 59

57 found

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

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

403

SearchSearch

31

43

64

20 40 56

28 33 47 59

89

Example: 61

57 failed

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

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

404

RevisionRevision

• Binary Tree

• Preorder, Inorder, Postorder Traveral

• Expression Trees

• Prefix, Infix, and Postfix notation

• Insert and Search

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

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

405

OverviewOverview

• Binary Search Trees.

• Hash Tables.

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

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

406

Recall - Binary Search Tree 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.

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

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

407

Example 1:

31

43

64

20 40 56

28 33 47 59

89

key is an integer

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

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

408

Fred

Dan Mary

Alan Eve

Bill Eric

Kate

Greg Len

Sue

Example 2: key is a string

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

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

409

Binary Tree NodeBinary Tree Node

entry

link to right child nodelink to left

child node

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

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 Binary Search Tree Node

Example 1:

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

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

411

Example 2:

Binary Search Tree Node Binary Search Tree Node

#define MAXLEN 15

struct TreeNodeRec{ char key[MAXLEN];

struct TreeNodeRec* leftPtr; struct TreeNodeRec* rightPtr;};

typedef struct TreeNodeRec TreeNode;

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

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

412

Recall:

maximumstring length

is fixed

#define MAXLEN 15

struct TreeNodeRec{ char key[MAXLEN];

struct TreeNodeRec* leftPtr; struct TreeNodeRec* rightPtr;};

typedef struct TreeNodeRec TreeNode;

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

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:

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

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.

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

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

415

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

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

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

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

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

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 NodeTree Node

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

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

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

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

420

MakeNodeMakeNode

• 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

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

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

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

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

422

0x2000

newNodePtr NULL

0x2000newNodePtr

0x20000x2000newNodePtr 3.3

NULL NULL

value 3.3

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

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

423

InorderInorder

• Inorder traversal of a Binary Search Tree always gives the sorted order of the keys.

void printInorder(TreeNode* nodePtr){

}

initially, pointerto root node

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

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

424

InorderInorder

• 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

}

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

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

425

InorderInorder

• 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);

}

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

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

426

InorderInorder

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

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

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

427

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

428

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

429

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

430

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

431

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

432

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

433

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

434

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

435

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

436

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

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

437

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

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

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

438

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 439: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

439

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 440: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

440

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 441: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

441

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 442: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

442

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 443: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

443

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 444: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

444

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 445: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

445

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 446: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

446

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 447: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

447

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 448: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

448

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 449: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

449

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 450: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

450

InorderInorder

void printInorder(TreeNode* nodePtr){ if (nodePtr != NULL){ printInorder(nodePtr->leftPtr); printf(“ %f”, nodePtr->key); printInorder(nodePtr->rightPtr); }}

nodePtr

Page 451: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

451

SearchSearch

31

43

64

20 40 56

28 33 47 59

89

Example: 59

57 found

Page 452: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

452

SearchSearch

31

43

64

20 40 56

28 33 47 59

89

Example: 61

57 failed

Page 453: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

453

Search: ChecklistSearch: 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.

Page 454: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

454

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL) { if (target < nodePtr->key) { nodePtr = search(nodePtr->leftPtr, target); } else if (target > nodePtr->key) { nodePtr = search(nodePtr->rightPtr, target); } } return nodePtr;}

Page 455: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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 SearchFunction Call to Search

Page 456: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

456

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.7nodePtr

Page 457: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

457

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.7nodePtr

Page 458: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

458

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.7nodePtr

Page 459: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

459

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.7nodePtr

Page 460: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

460

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.5nodePtr

Page 461: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

461

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.5nodePtr

Page 462: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

462

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.5nodePtr

Page 463: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

463

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.5nodePtr

Page 464: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

464

SearchSearch

TreeNode* search(TreeNode* nodePtr, float target){ if (nodePtr != NULL){ if (target < nodePtr->key) nodePtr = search(nodePtr->leftPtr, target); else if (target > nodePtr->key) nodePtr = search(nodePtr->rightPtr, target); } return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Find 0.5nodePtr

Page 465: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

465

InsertInsert

31

43

64

20 40 56

28 33 47 59

89

Example:57

Page 466: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

466

InsertInsert

31

43

64

20 40 56

28 33 47 59

89

Example:57

57

Page 467: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

467

InsertInsert

• Create new node for the item.

• Find a parent node.

• Attach new node as a leaf.

Page 468: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

468

Insert: RecursiveInsert: 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.

Page 469: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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 < nodePtr->key) { nodePtr->leftPtr = insert(nodePtr->leftPtr, item); } else if (item > nodePtr->key) { nodePtr->rightPtr = insert(nodePtr->rightPtr, item); }

return nodePtr;}

Page 470: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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 InsertFunction Call to Insert

Page 471: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

471

InsertInsert

TreeNode* insert(TreeNode* nodePtr, float item){ if (nodePtr == NULL)

nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Insert 0.9nodePtr

Page 472: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

472

InsertInsert

TreeNode* insert(TreeNode* nodePtr, float item){ if (nodePtr == NULL)

nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Insert 0.9nodePtr

Page 473: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

473

InsertInsert

TreeNode* insert(TreeNode* nodePtr, float item){ if (nodePtr == NULL)

nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Insert 0.9nodePtr

Page 474: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

474

InsertInsert

TreeNode* insert(TreeNode* nodePtr, float item){ if (nodePtr == NULL)

nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Insert 0.9nodePtr

Page 475: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

475

InsertInsert

TreeNode* insert(TreeNode* nodePtr, float item){ if (nodePtr == NULL)

nodePtr = makeTreeNode(item); else if (item < nodePtr->key) nodePtr->leftPtr = insert(nodePtr->leftPtr, item); else if (item > nodePtr->key) nodePtr->rightPtr = insert(nodePtr->rightPtr, item); return nodePtr;}

1.0

1.81.1

2.71.4

1.9

0.4 0.7

0.80.3

0.6

Insert 0.9nodePtr

0.9

Page 476: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

476

SortingSorting

To sort a sequence of items:

• Insert items into a Binary Search Tree.

• Then Inorder Traverse the tree.

Page 477: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

477

Sorting: AnalysisSorting: Analysis

• Insert (i+1)th item: ~ log2(i) comparisons

~ log2 n

• Average Case: O(n log(n))

Page 478: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

478

SortSort

Sort the following list into a binary search tree

0.51.0 0.7 2.12.5 3.6

Page 479: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

479

SortSort

0.51.0 0.7 2.12.5 3.6

1.0

Sort the following list into a binary search tree

Page 480: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

480

SortSort

0.51.0 0.7 2.12.5 3.6

1.0

2.5

Sort the following list into a binary search tree

Page 481: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

481

SortSort

0.51.0 0.7 2.12.5 3.6

1.0

2.50.5

Sort the following list into a binary search tree

Page 482: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

482

SortSort

0.51.0 0.7 2.12.5 3.6

1.0

2.50.5

0.7

Sort the following list into a binary search tree

Page 483: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

483

SortSort

1.0

2.50.5

0.7 3.6

Sort the following list into a binary search tree

0.51.0 0.7 2.12.5 3.6

Page 484: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

484

SortSort

0.51.0 0.7 2.12.5 3.6

1.0

2.50.5

0.7 3.62.1

Sort the following list into a binary search tree

Page 485: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

485

Sorting: AnalysisSorting: Analysis

• Insert (i+1)th item: ~ i comparisons

Example:

Insert: 1, 3, 7, 9, 11, 15

• Worst Case: O(n2)

Page 486: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

486

RevisionRevision

• Binary Search Tree

• Make Tree Node, Insert item, Search for an item, and Print Inorder.

• Tree sort.

Page 487: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

487

OverviewOverview

• Divide and Conquer

• Merge Sort

• Quick Sort

Page 488: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

488

SearchSearch

Divide and ConquerDivide and Conquer

SearchSearch

SearchSearch

Recall: Binary Search

Page 489: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

489

SortSort

Divide and ConquerDivide and Conquer

SortSort SortSort

SortSort SortSort SortSort SortSort

Page 490: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

490

Divide and ConquerDivide and Conquer

CombineCombine

CombineCombine CombineCombine

Page 491: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

491

Divide and ConquerDivide and Conquer

module sort(array){ if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) }}

Page 492: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

492

Divide and ConquerDivide and Conquer

module sort(array){ if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) }}

Page 493: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

493

Divide and ConquerDivide and Conquer

module sort(array){ if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) }}

Page 494: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

494

Divide and ConquerDivide and Conquer

module sort(array){ if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) }}

Page 495: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

495

Divide and ConquerDivide and Conquer

module sort(array){ if (size of array > 1) { split(array, firstPart, secondPart) sort(firstPart) sort(secondPart) combine(firstPart, secondPart) }}

Page 496: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

496

Merge SortMerge Sort

Sort Sort

Merge

Page 497: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

497

array:array:

sizesize

Merge SortMerge Sort

tmp:tmp:

tmpArrayPtr:tmpArrayPtr:

Page 498: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

498

array[mid]array[mid]array[0]array[0]

midmid (size - mid)(size - mid)

firstPart : array

secondPart : array + mid

Merge SortMerge Sort

Page 499: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

499

Merge SortMerge Sort

mergeListmergeList

tmp:tmp:

array:array:

Page 500: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

500

Merge SortMerge Sort

tmp:tmp:

array:array:

Page 501: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

501

Merge SortMerge Sort

array:array:

Page 502: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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);}

Page 503: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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]; } }}

Page 504: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

504

mergeArraysmergeArrays

3 5 15 28 30 6 10 14 22 43 50a:a: b:b:

aSize: 5aSize: 5 bSize: 6bSize: 6

Example:

tmp:tmp:

Page 505: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

505

mergeArraysmergeArrays

5 15 28 30 10 14 22 43 50a:a: b:b:

Example:

tmp:tmp:

i=0i=0

k=0k=0

j=0j=0

3 6

Page 506: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

506

mergeArraysmergeArrays

5 15 28 30 10 14 22 43 50a:a: b:b:

Example:

tmp:tmp:

i=0i=0

k=0k=0

3

j=0j=0

3 6

Page 507: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

507

mergeArraysmergeArrays

3 15 28 30 10 14 22 43 50a:a: b:b:

Example:

tmp:tmp:

i=1i=1 j=0j=0

k=1k=1

3 5

5 6

Page 508: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

508

mergeArraysmergeArrays

3 5 28 30 10 14 22 43 50a:a: b:b:

Example:

3 5tmp:tmp:

i=2i=2 j=0j=0

k=2k=2

6

15 6

Page 509: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

509

mergeArraysmergeArrays

3 5 28 30 6 14 22 43 50a:a: b:b:

Example:

3 5 6tmp:tmp:

i=2i=2 j=1j=1

k=3k=3

15 10

10

Page 510: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

510

10

mergeArraysmergeArrays

3 5 28 30 6 22 43 50a:a: b:b:

Example:

3 5 6tmp:tmp:

i=2i=2 j=2j=2

k=4k=4

15 10 14

14

Page 511: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

511

1410

mergeArraysmergeArrays

3 5 28 30 6 14 43 50a:a: b:b:

Example:

3 5 6tmp:tmp:

i=2i=2 j=3j=3

k=5k=5

15 10 22

15

Page 512: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

512

1410

mergeArraysmergeArrays

3 5 30 6 14 43 50a:a: b:b:

Example:

3 5 6tmp:tmp:

i=3i=3 j=3j=3

k=6k=6

15 10 22

2215

28

Page 513: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

513

1410

mergeArraysmergeArrays

3 5 30 6 14 50a:a: b:b:

Example:

3 5 6tmp:tmp:

i=3i=3 j=4j=4

k=7k=7

15 10 22

2815

28 43

22

Page 514: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

514

1410

mergeArraysmergeArrays

3 5 6 14 50a:a: b:b:

Example:

3 5 6tmp:tmp:

i=4i=4 j=4j=4

k=8k=8

15 10 22

3015

28 43

22

30

28

Page 515: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

515

1410

mergeArraysmergeArrays

3 5 6 14 50a:a: b:b:

Example:

3 5 6 30tmp:tmp:

i=5i=5 j=4j=4

k=9k=9

15 10 22

15

28 43

22

30

28 43 50

Done.

Page 516: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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++; } }}

Page 517: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

517

Merge Sort and Linked ListsMerge Sort and Linked Lists

Sort Sort

Merge

Page 518: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

518

Merge Sort AnalysisMerge 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.

Page 519: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

519

Quick SortQuick Sort

x < p p p <= x

Partition

Sort Sort

Page 520: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

520

Quick SortQuick SortExample:

5 89 35 10 24 15 37 13 20 17 70array:array:

size: 11size: 11

Page 521: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

521

Quick SortQuick SortExample:

5 89 35 14 24 15 37 13 20 7 70array:array:

“pivot element”

15

Page 522: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

522

partition:partition:

Quick SortQuick SortExample:

5 89 35 14 24 37 13 20 7 70array:array: 15

5 89 35 14 24 37 13 20 7 7015

7 14 5 13 15 35 37 89 20 24 70

index: 4index: 4

Page 523: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

523

Quick SortQuick SortExample:

array:array: 7 14 5 13 15 35 37 89 20 24 70

index: 4index: 4

indexindex (size - index - 1)(size - index - 1)

Page 524: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

524

Quick SortQuick SortExample:

indexindex (size - index - 1)(size - index - 1)

array[0]array[0] array[index + 1]array[index + 1]

firstPart : array

secondPart : array + index + 1

14 5 13 15 37 89 20 24 707 35

Page 525: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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 SortQuick Sort

Page 526: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

526

Partition: ChecklistPartition: Checklist

p

p

00

p x < p p <= x

p x < p p <= x

px < p p <= x

Page 527: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

527

PartitionPartitionExample:

5 89 35 14 24 15 37 13 20 7 70array:array: 15

mid: 4mid: 4

15 89 35 14 24 5 37 13 20 7 70

5

00

Page 528: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

528

PartitionPartitionExample:

array:array:

k=1k=1

15 89 35 14 24 5 37 13 20 7 70

00

Page 529: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

529

PartitionPartitionExample:

array:array:

k:1k:1

15 89 35 14 24 5 37 13 20 7 70

index:0index:0

89

Page 530: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

530

PartitionPartitionExample:

array:array:

k:2k:2

15 89 35 14 24 5 37 13 20 7 70

index:0index:0

35

Page 531: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

531

PartitionPartitionExample:

array:array:

k:3k:3

15 89 35 14 24 5 37 13 20 7 70

index:0index:0

14

Page 532: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

532

PartitionPartitionExample:

array:array:

k:3k:3

15 89 35 14 24 5 37 13 20 7 70

index:1index:1

8914

Page 533: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

533

PartitionPartitionExample:

array:array:

k:4k:4

15 14 35 89 24 5 37 13 20 7 70

index:1index:1

24

Page 534: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

534

PartitionPartitionExample:

array:array:

k:5k:5

15 14 35 89 24 5 37 13 20 7 70

index:1index:1

5

Page 535: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

535

PartitionPartitionExample:

array:array:

k:5k:5

15 14 35 89 24 5 37 13 20 7 70

index:2index:2

5 35

Page 536: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

536

PartitionPartitionExample:

array:array:

k:6k:6

15 14 89 24 37 13 20 7 70

index:2index:2

5 35 37

Page 537: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

537

PartitionPartitionExample:

array:array:

k:7k:7

15 14 89 24 37 13 20 7 70

index:2index:2

5 35

etc...

Page 538: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

538

PartitionPartitionExample:

array:array:

k:11k:11

15 14 13 7 37 89 20 24 70

index:4index:4

5 35

Page 539: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

539

PartitionPartitionExample:

array:array: 15 14 13 7 37 89 20 24 70

index:4index:4

5 35

Page 540: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

540

PartitionPartitionExample:

array:array: 15 14 13 7 37 89 20 24 70

index:4index:4

5 35157

x < 15x < 15 15 <= x15 <= x

Page 541: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

541

Example:

array:array: 15 14 13 7 37 89 20 24 705 35157

x < 15x < 15 15 <= x15 <= x

pivot now incorrect position

Page 542: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

542

Example:

14 13 37 89 20 24 705 357

14 1357 37 89 20 24 7035

15

Sort Sort

Page 543: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

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;}

Page 544: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

544

Quick Sort AnalysisQuick Sort Analysis

• Most of the work done in partitioning.

• Need to be careful of choice of pivot.– Example: 2, 4, 6, 7, 3, 1, 5

• Average case takes O(n log(n)) time.

• Worst case takes O(n2) time.

Page 545: 1 Lectures on data structures and C 3ed CS(CSI33) By, CHANDRASHEKAR A.M

copy right (version1.0) SUNITHA C.N,CS&E dept,SJCE

545

RevisionRevision

• Merge Sort

• Quick Sort