0% found this document useful (0 votes)
4 views

3 Arrays

To master in array

Uploaded by

yuvarajacb11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

3 Arrays

To master in array

Uploaded by

yuvarajacb11
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Problem Solving

using Arrays

Rupesh Nasre.
Mentor TAs: Ahmed, Vivek, Vimala, Akash,
Kankan, Rahul, Swati, Akshay, Ashok, Keshav

IIT Madras
May 2022
Dennis Ritchie

Creator of C

Co-creator of Unix

Turing Award 1983

Nobel Prize in Computing
Ken Thompson Dennis Ritchie

Photos from wikipedia and NIHF


Week Problems Tools

0 Solve equations, find weighted sum. Data types, expressions, assignments


1 Find max, convert marks to grade. Conditionals, logical expressions
2 Find weighted sum for all students. Loops

3 Encrypt and decrypt a secret message. Character arrays

low
4 Our first game: Tic-tac-toe 2D arrays

F
rol
5 Making game modular, reuse. Functions

nt
Co
6 Find Hemachandra/Fibonacci numbers. Recursion

7 Encrypt and decrypt many messages. Dynamic memory, pointers

8 Maintain student records. Aggregate data types

9 Search and sort student records. Searching and sorting algorithms

A Reduce memory wastage. Linked lists

B Implement token system in banks. Queues

a
Dat
C IRCTC-like ticket booking system File handling
3
D Putting it all together All the above
Arrays are uniform aggregates.
int ages[7];
int age;

Ages of all the students age 19

Record of all the books 18
Data 18
4315348

A name 20

18

17
ii = 0;
18

Assignments ii < nhw
18

Conditionals printf(...) Control Flow

Loops ii = ii + 1

End of program 4
Future Connect:

Arrays are uniform aggregates.


Different data types can
be put together using
struct.

int ages[7];
int age;
int
intmain()
main(){ {
int age 4415320 19
intages[7];
ages[7];
char
charname[6];
name[6]; 18
4415324 18
ages[0] 4315348
ages[0]==19;
19;ages[1]
ages[1]==18;
18;…

name[0]
name[0] = 'A'; name[1] = 'M';......
= 'A'; name[1] = 'M'; 4415328 20
char name[6];
for
for(int
(intiiii==0;0;ii ii<<6;6;++ii)
++ii) 441532C 18
printf("%d: %d
printf("%d: %d %c\n", %c\n", 6415396 'A'
ii,ii,ages[ii],
ages[ii],name[ii]);
name[ii]); 4415330 17
}} 6415397 'M'
4415334 18
6415398 'A'
6
5 4415338 18
4 6415399 'N'
3
2
01 641539A
Two ways to access a cell:
'\0' 1. Using the cell's address
2. If I know the start address
641539B ?? of the array, then using an5
offset.
Arrays and loops are friends.
#define
#defineNN87
87
int
intmain()
main(){ { $ ./a.out Input redirection
int
intmarks[N];
marks[N]; 87
for
for (intiiii==0;0;ii ii<<N;
(int N;++ii)
++ii) 86
scanf("%d", &marks[ii]);
scanf("%d", &marks[ii]); 57 $ ./a.out < data.txt
int
intsum
sum==0;0; 93 Average = 80.54
for
for(int
(intiiii==0;0;ii ii<<N;
N;++ii)
++ii) 59 5
6
sum += marks[ii]; 96 4
sum += marks[ii]; 3
2
printf("Average 01
printf("Average==%.2f\n", %.2f\n",(float)sum
(float)sum/ /N);
N); ...
}}

&marks[0] 4415320 87 marks[0]


Name of the array is marks + ii is the
same as the address of &marks[1] 4415324 86 marks[1] address of the ii‘th
its first element. element.
&marks[2] 4415328 57 marks[2]
So, marks == &marks[0] marks + ii == &marks[ii]
&marks[3] 441532C 93 marks[3]
6
...

...
...

...
Accessing arrays of different types
int=4, intarray[10]=40
int
#define
char
#define
i,
char
iarray[10];
int i, iarray[10];
N 87
c,
N c,carray[10];
87carray[10];
char=1, chararray[10]=10
float=4,#define
double=8,
floatarray[10]=40
#define NN87 87
darray[10]=80
bytes
float
floatf,f,farray[10];
farray[10]; int addresses: 0x7fff3a86a3f0 0x7fff3a86a3f4
int main()
double { d, darray[10]; int main() {
int main()0x7fff3a86a453
{
int main()
double { d, darray[10]; char addresses: 0x7fff3a86a454
int marks[N]; char name[N];
char name[N];
int marks[N];
for (int ii =
printf("int=%ld, 0; ii < N; ++ii)
intarray[10]=%ld\n", sizeof(i), for
for(int
(intiiii==0;0;iiii<<N;
sizeof(iarray)); N;++ii)
++ii)
for (int ii = 0; ii <intarray[10]=%ld\n",
printf("int=%ld, N; ++ii) sizeof(i), sizeof(iarray));
scanf("%d",
printf("char=%ld, &marks[ii]);
chararray[10]=%ld\n", sizeof(char), scanf("%c",
sizeof(carray)); &name[ii]);
scanf("%c", &name[ii]);
scanf("%d", chararray[10]=%ld\n",
printf("char=%ld, &marks[ii]); sizeof(char), sizeof(carray));
printf("float=%ld,
int sum ==0;0;
printf("float=%ld, floatarray[10]=%ld\n", sizeof(f), sizeof(farray));
floatarray[10]=%ld\n", sizeof(f), int sum ==0;0;
sizeof(farray));
int sum
printf("double=%ld, darray[10]=%ld\n", sizeof(d), int sum
sizeof(darray));
for (int ii = 0;
printf("double=%ld,ii < N; ++ii)
darray[10]=%ld\n", sizeof(d), for
for(int
(intiiii==0;0;iiii<<N;
sizeof(darray)); N;++ii)
++ii)
for (int ii = 0; ii < N; ++ii)
sum += marks[ii]; sum += name[ii];
sum += name[ii];
printf("intsum += marks[ii];
addresses: %p %p\n", &iarray[0], &iarray[1]);
printf("Average
printf("int ==%.2f\n",
addresses: %p (float)sum
%p\n", / /N);
&iarray[0], printf("Average
&iarray[1]);
printf("Average ==%.2f\n",
%.2f\n",(float)sum
(float)sum/ /N);
N);
printf("Average
printf("char addresses: %.2f\n",
%p (float)sum
%p\n", N);
&carray[5], &carray[6]);
}} }
printf("char addresses: %p %p\n", &carray[5],} &carray[6]);

4415320 87 6415396 'A'


Compiler generates
4415324 86 code to access 6415397 'M'
appropriate
4415328 57 memory location 6415398 'A'
based on type.
441532C 93 6415399 'N' 7
...

...
...

...
Find Max and SecondMax
#include <limits.h>
////initialize
initializearray
array
int
int arr[] = {20,19,
arr[] = {20, 19,84,
84,-32,
-32,54,
54,63,
63,48};
48};
int N = sizeof(arr) / sizeof(arr[0]); 20
int N = sizeof(arr) / sizeof(arr[0]);
////check
checkfor foratatleast
leasttwotwoelements
elements 19
ifif(N < 2)
(N < 2) { {
printf("Add
printf("Addaafew fewmore
moreelements.\n");
elements.\n"); 84
exit(1);
exit(1);
}} Alternatively, max and -32
int
intmaxmax ==-1; INT_MIN;
-1; smax could be for the
int
intsmax
smax==INT_MIN;
-1;
-1; first two elements. for 54
loop can start from 2.
////find
findmax maxand andsmax
smax 63
for
for (int ii = 0; ii <N;
(int ii = 0; ii < N;++ii)
++ii){ {
ifif(arr[ii]
(arr[ii]>>max)
max){ { 48
smax
smax==max; max;
max = arr[ii];
max = arr[ii];
} }else
elseifif(arr[ii]
(arr[ii]>>smax)
smax)
smax = arr[ii];
smax = arr[ii];
}}
printf("max
printf("max==%d, %d,smax
smax==%d\n",
%d\n",max,
max,smax);
smax); 8
Search
////initialize
initializearray
array Is 54 present?
ar

int {'H', 'e',


"Hello World";
'l', 'l', 'o', ' ', 'W',63,
'o', 'r', 'l', 'd'};
int arr[] = {20,19,
arr[] = {20, 19,84, 84,-32,-32,54, 54, 63,48};48}; Yes, at index 4.
ch

int N = sizeof(arr) / sizeof(arr[0]); 20


int N = sizeof(arr) / sizeof(arr[0]);
Is 55 present?
////get
getsearch
searchkey
key No. 19
ar

int key;
%c

int key;
ch

scanf("%d",
scanf("%d",&key);
&key); 84

////search
searchininthe thearray
array A variable is -32
for
for (int ii = 0; ii <N;
(int ii = 0; ii < N;++ii)
++ii) accessible only within
ifif(arr[ii] its scope.
(arr[ii] == key){ {
== key) 54
printf("Found
printf("Foundatat%d\n",
%d\n",ii);ii);
break;
break; Two variables of the
63
}} same name cannot be
////print
printnot notfound
found defined in the same
ii is inaccessible. scope. 48
ifif(ii(ii== N)
== N)
printf("Not
printf("Notpresent\n");
present\n");
But another scope
may redefine a
Alternative approaches: variable of the same
1. Use a flag to indicate whether the key was found. name.
2. Remove break to search for all the instances 9
(but be careful).
Let's Play

One player thinks of a number from 1..1000,
and the other player finds it out in 10 questions.

Only one type of question is allowed

Is your number less than some value? Can we always
perform a

Two answers are allowed binary search?

Does this problem have a similarity with



Yes ●
Open page number 273
Binary Search

Check the meaning of supercalifragilisticexpialidocious in your dictionary

No ●
Tell me the phone number of Star Garage from a directory

How is it different from our previous


problem of searching in an array? Linear Search

10
Binary Search You
int arr[] = {-5, -3, 0, 4, 43, 58, 59, 64, 70, 74, 75, 79, 81, 88,
Write the code.
92,may
93};need start
int
intarr[]
arr[]=={-5,
{-5,-3,
-3,0,0,4,4,43,
43,58,
58,59,
59,64,
64,70,
70,74,
74,75,
75,79,
79,81,
81,88,
88,92,
92,93};
93};
int N = sizeof(arr) / sizeof(arr[0]); and end offsets, along
int N = sizeof(arr) / sizeof(arr[0]); with their middle index.

Expects
int
intkey;
key;
sorted array (ascending or descending)
scanf("%d",
scanf("%d",&key);
&key);

Reduces search space by half in every step.
int start, end, mid;
int start, end, mid;
//start
initialize
==0,0,endstart,==end,
N-1; mid
Thus, needs log(n) steps to complete search.
● //start
while
initialize
while(there
(end
(there
start,
end
are
(end- -start
are
end,
N-1; mid
elements
>= to be searched) {
>=0)0){ { to be searched) {
startelements
mid
mid==(start (start++end)
end)/ /2;2;
● Log (1000)
ifif(arr[mid] == key)= { {9.97. Hence 10 questions sufficed.
(arr[mid]
2 == key)
printf("Found
printf("Foundatat%d\n",%d\n",mid);
mid); Will it improve performance if I
break;

Linear
} }else search
break;
{ needed time proportional to
split the array inton. In
three the
parts?
elseif{if(arr[mid] < key)
(arr[mid] < key)
worst ////whatcase,
start mid++it
should
start==should
what mid I1;
Ido?made n comparisons.
do?
1;
}else
}elseend end==midmid- -1;1;
//printf("start
//printf("start ==%d,
key 74end=%d\n",
=%d, end=%d\n",start,
start,end);
end);
}}
ifif(arr[mid]
(arr[mid]!=!=key) key)
-5 printf("Not
printf("Notpresent\n");
-3 0 4 42 58 59 64 70 74 75 79 81 88 92 93
present\n");

11
Problem: Reverse the array.
int
intarr[]
arr[]=={-5,
{-5,-3,
-3,0,0,4,4,43,
43,58,
58,59,
59,64,
64,70,
70,74,
74,75,
75,79,
79,81,
81,88,
88,92,
92,93};
93};
int N = sizeof(arr) / sizeof(arr[0]);
int N = sizeof(arr) / sizeof(arr[0]);
////array
arrayreversal
reversal #define swap(arr, indexx, indexy) { \
for
for (int ii =0;0;iiii<<NN/ /2;2;++ii)
(int ii = ++ii) int tmp = arr[indexx]; \
swap(arr, ii, N-1-ii);
swap(arr, ii, N-1-ii); arr[indexx] = arr[indexy]; \
arr[indexy] = tmp; \
for
for(int
(intiiii==0;0;iiii<<N;N;++ii)
++ii) }
printf("%d ", arr[ii]);
printf("%d ", arr[ii]);
printf("\n");
printf("\n");

12
Problem: Rotate the array.
int
intarr[]
arr[]=={-5,
{-5,-3,
-3,0,0,4,4,43,
43,58,
58,59,
59,64,
64,70,
70,74,
74,75,
75,79,
79,81,
81,88,
88,92,
92,93};
93};
int N = sizeof(arr) / sizeof(arr[0]);
int N = sizeof(arr) / sizeof(arr[0]);
////array
arrayrotate
rotateright
right
int last = arr[N-1]; // Alternatively // Further alternatively
int last = arr[N-1]; for (int ii = N-1; ii > 0; --ii) int saved = arr[N-1];
for
for(int
(intiiii==N-2;
N-2;iiii>=
>=0;0;--ii)
--ii)
arr[ii + 1] = arr[ii]; swap(arr, ii, ii - 1); for (int ii = 0; ii < N; ++ii) {
arr[ii + 1] = arr[ii]; int tmp = arr[ii];
arr[0]
arr[0] =last;
= last; arr[ii] = saved;
for saved = tmp;
for(int
(intiiii==0;0;iiii<<N;N;++ii)
++ii) }
printf("%d ", arr[ii]);
printf("%d ", arr[ii]);
printf("\n");
printf("\n");
93 -5 -3 0 4 43 58 59 64 70 74 75 79 81 88 92

How would you perform a left-rotate?


How to perform a k-rotate?
What do you require to perform a k-rotate in a single loop?

13
Problem: Duplicates.
int
intarr[N+1];
arr[N+1];int
intfreq[N+1];
freq[N+1]; 42 54 3 65 32
54 37 59 37 47
////read
readinput
input 48 42 39 29 22
for
for (int ii==1;1;iiii<=
(int ii <=N;
N;++ii)
++ii) 28 32 51 54 35
scanf("%d", &arr[ii]);
scanf("%d", &arr[ii]); 21 11 8 23 52
16 35 33 56 65
////calculate
calculatefrequencies
frequencies 4 42 55 52
for
for (int ii = 1;iiii<=
(int ii = 1; <=N;
N;++ii)
++ii)
freq[arr[ii]]++; Duplicate for 32
freq[arr[ii]]++; Duplicate for 35
////print Duplicate for 37
printduplicates
duplicates Duplicate for 42
for
for (int ii==1;1;iiii<=
(int ii <=N;N;++ii)
++ii) Duplicate for 52
ifif(freq[ii] == 0) ; // printf("Student %d is absent\n", ii);
(freq[ii] == 0) ; // printf("Student %d is absent\n", ii); Duplicate for 54
else
elseifif(freq[ii]
(freq[ii]>>1)1)printf("Duplicate
printf("Duplicatefor for%d\n",
%d\n",ii);ii); Duplicate for 65

Alternatively,
- For each number, check if it repeats.
- Sort the numbers in ascending order and check consecutive numbers.

Given an attendance list, find the student who has signed more than once
(assume roll numbers 1 to 87). 14
Problem: Negative then Positive.
int
intarr[N]
arr[N]=={53,
{53,33,
33,0,0,-4,
-4,43,
43,9,9,58,
58,22,
22,-59,
-59,4,4,-7,
-7,74,
74,55,
55,-9,
-9,23,
23,8,8,2,2,-3};
-3};
////Keep
Keeptwo twoindices
indicesleftleftand
andright
right
-3 -9 -7 -4 -59 9 58 22 43 4 0 74 55 33 23 8 2 53
////Start
Startleft
leftfrom
from0,0,right
rightfrom
fromN-1
N-1
////IfIfleft
left number is positive andright
number is positive and rightnumber
numberisisnegative,
negative,swap.
swap.
////Increment left if the number is
Increment left if the number is negative. negative.
////Decrement
Decrementright rightififthe
thenumber
numberisispositive.
positive.
for
for(int
(intleft
left==0,0,right
right==N-1;
N-1;left
left<<right;
right;) ){ {
ifif(arr[left]
(arr[left]>=>=00&&&&arr[right]
arr[right]<<0)0)swap(arr,
swap(arr,left,
left,right);
right);
ifif(arr[left] < 0) left++;
(arr[left] < 0) left++;
ifif(arr[right]
(arr[right]>= >=0)0)right--;
right--;
}}

Given a list of numbers (boys+girls / CS+nonCS / Mahanadi+Ganga /


Negative+Positive), move all negatives to the left (in any order). 15
Problem: Merge sorted arrays
int
intA[]
A[]=={-3,
{-3,0,0,43,
43,58,
58,64,
64,79,
79,93};
93};
int
int B[] = {-5, 4, 59, 70, 74, 75, 81,88,
B[] = {-5, 4, 59, 70, 74, 75, 81, 88,92};
92};
int NA = sizeof(A) / sizeof(A[0]);
int NA = sizeof(A) / sizeof(A[0]);
int NB = sizeof(B) / sizeof(B[0]); -5 -3 0 4 43 58 59 64 70 74 75 79 81 88 92 93
int NB = sizeof(B) / sizeof(B[0]);
int
intC[NA
C[NA++NB];
NB];////variable
variablelength
lengtharray,
array,allowed
allowedfrom
fromANSI
ANSIC99
C99standard.
standard.
C[indexC] = A[indexA];
int
intindexA
indexA==0,0,indexB
indexB==0,0,indexC
indexC==0;0; indexA++;
indexC++;
while
while(indexA
(indexA<<NANA&&&&indexB
indexB<<NB)
NB){ {
ifif(A[indexA]
(A[indexA]<<B[indexB])
B[indexB])C[indexC++]
C[indexC++]==A[indexA++];
A[indexA++];
else C[indexC++] = B[indexB++];
else C[indexC++] = B[indexB++];
}}
while
while(indexA
(indexA<<NA)
NA)C[indexC++]
C[indexC++]==A[indexA++];
A[indexA++];
while (indexB < NB) C[indexC++] = B[indexB++];
while (indexB < NB) C[indexC++] = B[indexB++];

Extend the program to perform in-situ merge.


Array A has two sorted sequences.

C = A merge B, with A and B are sorted.


C is also sorted. 16
char array
char
chararr[]
//arr[] =="Hello";
//initialize
initialize array
"Hello";
array arr {H', 'e', 'l', 'l', 'o'} "Hello" "Bye" ""
char two[]
char =
arr[]" World";
= ={'H',
{'H','e',
'e','l','l','l','l','o'};
"Hello";
char two[] char arr[] = " World"; 'o'};
int N = sizeof(arr) / sizeof(arr[0]); N 5 6 4 1
int N = sizeof(arr) / sizeof(arr[0]);
int ii;
int ii;
for
for(ii(ii
//= 0;0;arr[ii] !=!=key
'\0';
'\0';++ii)
//get
=get search
arr[ii]
search key ++ii) Strings end with ascii value zero.
; ; key;
int
int key;
int arrlen
scanf("%c",
int arrlen ==ii;ii; &key);
scanf("%c", &key);
printf("Length
printf("Length of %sisis%d\n",
of %s %d\n",arr, arr,arrlen);
arrlen); This can be exploited in various
////search
searchininthe thearrayarray string related functions:
for (ii =
int
for (iiint 0;
ii;
= 0; arr[ii] != '\0'; ++ii) - computing length of a string
ii; arr[ii] != '\0'; ++ii)
ifif(arr[ii]
for >=ii <
'a''a' && arr[ii]
arr[ii]<= <='z')
for(ii (ii==0;0;>=
(arr[ii] ii < N; N; ++ii)
&& ++ii) 'z') - converting a string to upper case
arr[ii]
ifarr[ii] += 'A' - 'a';
if(arr[ii]
+===
(arr[ii] ==key)
'A' 'a';{ {
-key) - concatenating two strings
printf("Uppercase %s\n",
%s\n",arr);
printf("Found atat%d\n",
printf("Uppercase printf("Found arr); %d\n",ii);ii); Write these codes.
break;
break;
char cat[100];
char cat[100]; } }
for (ii//= 0;
print arr[ii]
not !=!='\0';
'\0';++ii)
for (ii//=print notfound
0; arr[ii] found ++ii)
ifcat[ii]
(ii ==
ifcat[ii]
=
(ii ===N)
arr[ii];
N) arr[ii];
for (int jj = 0; 0; two[jj]!=!=
two[jj]
printf("Not
for (int jj = printf("Not '\0';
'\0';++ii,
present\n"); ++ii,++jj) ++jj)
present\n");
cat[ii] = two[jj];
cat[ii] = two[jj];
cat[ii] \0 is an escape sequence.
cat[ii] ='\0';
= '\0';
printf("%s
printf("%s++%s %sisis%s\n",%s\n",arr, arr,two, two,cat);
cat); 17
Escape Sequences
int
intmain()
main(){ { Carriage
CarriageReturn
Return
printf("Hello\rCarriage
printf("Hello\rCarriageReturn\n");
Return\n"); Backspac:
Backspac:Check
Check
printf("Backspace\b: Check\n");
printf("Backspace\b: Check\n"); Alert:
Alert: Do youhear
Do you hearit?
it?
printf("Alert\a:
printf("Alert\a:Do
Doyou
youhear
hearit?\n");
it?\n"); Formfeed
Formfeed
printf("Formfeed\fUseful for printing\n");
printf("Formfeed\fUseful for printing\n"); Useful
Usefulfor
forprinting
printing
printf("T\ta\tb\n");
printf("T\ta\tb\n"); TT aa bb
printf("Vertical\vTab\n");
printf("Vertical\vTab\n"); Vertical
Vertical
printf("Back\\slash\n");
printf("Back\\slash\n"); Tab
Tab
printf("%cSingle
printf("%cSinglequote%c\n",
quote%c\n",'\'',
'\'','\'');
'\''); Back\slash
Back\slash
printf("\"Double quote\"\n");
printf("\"Double quote\"\n"); 'Single
'Singlequote'
quote'
printf("\x45\x73\x63\x61\x70\x65
printf("\x45\x73\x63\x61\x70\x65Character\n");
Character\n"); "Double
"Doublequote"
quote"
printf("\117\143\164\141\154\n");
printf("\117\143\164\141\154\n"); Escape Character
Escape Character
printf("Unicode
printf("Unicode\u20B9\n");
\u20B9\n"); Octal
Octal
}} Unicode₹₹
Unicode

18
System of Equations
4x – y - 5z = 7 4 -1 -5 x 7

2x + 3y - 4z = 9 2 3 -4 y = 9

x + z = 22 1 0 1 z 22

Can be represented Can be represented


using 1D arrays or 2D using 1D arrays.
array.

2D arrays allow us to access an element using its


row and column directly (e.g., mat[row][col]).
Useful in image processing, tabular data, etc.
19
2D Arrays / Matrices
1D Array
#include <stdlib.h>
int
intmat[ROWS][COLS];
mat[ROWS][COLS];
Declaration / Definition int mat[ROWS * COLS];
23
for
for(int
(intiiii==0;0;iiii<<ROWS;
ROWS;++ii)
++ii) 2
for
for (int jj = 0; jj < COLS;++jj)
(int jj = 0; jj < COLS; ++jj)
Initialization mat[ii * COLS + jj] = ...
mat[ii][jj] ...
mat[ii][jj] = rand() %100;
= rand() % 100;
6
for
for(int
(intiiii==0;0;iiii<<ROWS;
ROWS;++ii) ++ii){ { 45
for
for(int(intjj jj==0;0;jj jj<<COLS;
COLS;++jj)
++jj) Printing
printf("%4d", mat[ii][jj]); 87
printf("%4d", mat[ii][jj]);
printf("\n");
printf("\n"); ...
}}
5
...
23 2 88 77 ... 83 9 6 4
45 87 99 32 ... 6 32 5 mat[1][COLS – 1]
33
ROWS

... ... ... ... ... ... ... ... 4


43 85 43 33 ... 9 4 33 83
4 83 67 56 ... 56 2 0 mat[ROWS – 1][COLS – 1] ... 20
COLS 0
Problem: Saddle Point
.

A saddle point is minimum in its row and
maximum in its column (used in minimax method).
8 11 23 6 5
33 0 9 -3 3
20 -4 6 5 5
12 8 9 7 10

Does it always exist?


Can there be multiple saddle points?
Write the code.

21
Image: wikipedia
Sorting

A fundamental operation

Elements need to be stored in increasing order.

Some methods would work with duplicates.

Algorithms that maintain relative order of duplicates
from input to output are called stable.

Comparison-based methods

Insertion, Bubble, Selection, Shell, Quick, Merge

Other methods

Radix, Bucket, Counting
22
Sorting Algorithms at a Glance
Algorithm Worst case Average case
complexity complexity
Bubble O(n2) O(n2)
Insertion O(n2) O(n2)
Shell O(n2) Depends on
increment
sequence
Selection O(n2) O(n2)
Heap O(n log n) O(n log n)
Quick O(n2) O(n log n)
depending on
partitioning
Merge O(n log n) O(n log n)
Bucket O(n α log α) Depends on α 23
Bubble Sort

Compare adjacent values and swap, if required.

How many times do we need to do it?

What is the invariant?

After ith iteration, i largest numbers are at their final
places.

An element may move away from its final position in
the intermediate stages (e.g., check the 2nd element
of a reverse-sorted array).

Best case: Sorted sequence

Worst case: Reverse sorted (n-1 + n-2 + ... + 1 + 0)
24

Classwork: Write the code.
Bubble Sort
for
for(ii
(ii==0; 0;iiii<<N;N;++ii)
++ii)
for
for(jj (jj==0;0;jjjj<<NN--1;1;++jj)
++jj)
ifif(arr[jj]
(arr[jj]>>arr[jj
arr[jj++1])
1])swap(jj,
swap(jj,jjjj++1);
1); Not using ii

for
for(ii
(ii==0; 0;iiii<<NN--1;1;++ii)
++ii)
for
for(jj (jj==0;0;jjjj<<NN––iiii--1;
1;++jj)
++jj) O(n2)
ifif(arr[jj]
(arr[jj]>>arr[jj
arr[jj++1])
1])swap(jj,
swap(jj,jjjj++1);
1);


Best case: Sorted sequence

Worst case: Reverse sorted (n-1 + n-2 + ... + 1 + 0)

What do we measure?

Number of comparisons

Number of swaps (bounded by comparisons)
25

Number of comparisons remains the same!
Insertion Sort

Consider ith element and insert it at its place w.r.t.
the first i elements.

Resembles insertion of a playing card.

Invariant: Keep the first i elements sorted.

Note: Insertion is in a sorted array.

Complexity: O(n log n)?

Yes, binary search is O(log n).
But are we doing more work?

Best case, Worst case?

Classwork: Write the code. 26
Insertion Sort
for
for(ii
(ii==11;;iiii<<N; N;++ii)
++ii){{
int
intkey
key==arr[ii];
arr[ii]; ith element
int
intjjjj==iiii--1;
1;
while
while(jj(jj>=
>=00&&&&key
key<<arr[jj])
arr[jj]){{
arr[jj
arr[jj++1]
1]==arr[jj];
arr[jj]; Shift elements
--jj;
--jj; 0 + 1 + 2 + ... n-1
}}
arr[jj
arr[jj++1]1]==key;
key; At its place
}}

Best case: Sorted: while loop is O(1)

Worst case: Reverse sorted: O(n2)

27
Selection Sort

Approach: Choose the minimum element, and
push it to its final place.

What is the invariant?

First i elements are at their final places after i
iterations.

Classwork: Write
for the code. ++ii){ {
for(ii(ii==00; ;iiii<<NN- -1;1;++ii)
int
intiimin
iimin==ii;ii;
for
for(jj(jj==iiii++1;1;jjjj<<N;
N;++jj)
++jj)
ifif(arr[jj] Find min.
(arr[jj]<<arr[iimin])
arr[iimin])
iimin
iimin==jj;jj;
swap(iimin,
swap(iimin,ii); ii);
}} 28
Shell Sort

The number of shiftings is too high in insertion
sort. This leads to high inefficiency.

Can we allow some perturbations initially and
fix them later?

Approach: Instead of comparing adjacent
elements, compare those that are some
distance apart.

And then reduce the distance.
Input 81 94 11 96 12 35 17 95 28 58 41 75 15

This sequence of distances is called increment
gap=5 35 17 11
sequence. 28 12 41 75 15 96 58 81 94 95
gap=3 28 12 11 35 15 41 58 17 94 75 81 96 95
29
gap=1 11 12 15 17 28 35 41 58 75 81 94 95 96
Shell Sort
for (gap = N/2; gap; gap /= 2)
for
for(ii
(ii==...
...;;iiii<<N;
N;++ii)
++ii){{ ith element
int
intkey
key==arr[ii];
arr[ii];
int
intjjjj==iiii--1;
1;
while
while(jj (jj--gap
gap>=>=00&&
&&key key<<arr[jj
arr[jj--gap])
gap]){{
arr[jj
arr[jj++1]
1]==arr[jj];
arr[jj]; Shift elements
jjjj-=
-=gap;
gap;
}}
arr[jj
arr[jj++1] 1]==key;
key; At its place
}}


Best case: Sorted: while loop is O(1)

Worst case: O(n2)
30
Heapsort
Given N elements, N storage

build a heap and O(N) time

then perform N deleteMax, O(N log N) time

store each element into an array. O(N) time and N space

O(N log N) time and 2N space


for
for(int
(intiiii==0;0;iiii<<nelements;
nelements;++ii)
++ii){ {
h.hide_back(h.deleteMax()); Can
}}
h.hide_back(h.deleteMax()); Canwe
weavoid
avoidthe
the
second array?
second array?
h.printArray(nelements);
h.printArray(nelements);
Quicksort

Approach:

Choose an arbitrary element (called pivot).

Place the pivot at its final place.

Make sure all the elements smaller than the pivot
are to the left of it, and ... (called partitioning)

Divide-and-conquer.
void
voidquick(int
quick(intstart,start,int
intend)
end){ {
ifif(start
(start<<end)
end){ { Crucially decides
int
intiipivot
iipivot==partition(start,
partition(start,end);
end); the complexity.
quick(start,
quick(start,iipivot
iipivot- -1);
1);
quick(iipivot
quick(iipivot++1,1,end);
end);
}} 32
}}
Merge Sort

Divide-and-Conquer

Divide the array into two halves

Sort each array separately

Merge the two sorted sequences

Worst case complexity: O(n log n)

Not efficient in practice due to array copying.

Classwork: Write
void the code.start,
voidmergeSort(int
mergeSort(int start,int
intend)
end){ {
ifif(start
(start<<end)
end){ {
int
intmid
mid==(start
(start++end)
end)/ /2;2;
mergeSort(start,
mergeSort(start,mid);
mid);
mergeSort(mid
mergeSort(mid++1,1,end);
end);
merge(start,
merge(start,mid,
mid,end);
end);
}} 33

}}
Bucket Sort

Hash / index each element into a bucket.

Sort each bucket.

use other sorting algorithms such as insertion sort.

Output buckets in increasing order.

Special case when number of buckets >=
maximum element value.

Unsuitable for arbitrary types.

34
Counting Sort

Bucketize elements.

Find count of elements in each bucket.

Perform prefix sum.

Copy elements from buckets to original array.
Original array 4 1 4 9 11 7 8 1 3 4

Buckets 1, 1 3 4, 4, 4 7 8 9 11

Bucket sizes 2 0 1 3 1 0 1 0 1 1

Starting index 0 2 2 3 6 7 7 8 8 9

Output array 1 1 3 4 4 4 7 8 9 11 35
Radix Sort O(P * (N + B))
P = passes
N = elements

Generalization of bucket sort. B = buckets


Radix sort sorts using different digits.

At every step, elements are moved to buckets
based on their ith digits, starting from the least
significant digit.

Classwork: 33, 453, 124, 225, 1023, 432, 2232
64 8 216 512 27 729 0 1 343 125
0 1 512 343 64 125 216 27 8 729
00, 01, 512, 125, 343 64
08 216 27,
729
000, 125 216 343 512 729
001,
008,
027, 36
064
String Functions
char char
chararr[]
arr[]=="Hello";
chararr[]
arr[]=="Hello";
"Hello"; "Hello";
char char
char two[] = "World";
two[] = "
char two[] = "World";
two[] = " World"; World";
int int
intarrlen
arrlen==strlen(arr);
intii;ii; strlen(arr);
for printf("Length
printf("Lengthofof%s
%sisis%d\n",
%d\n",arr,
arr,arrlen);
for(ii(ii==0;0;arr[ii]
arr[ii]!=!='\0';
'\0';++ii)
++ii) arrlen);
;;
int for
for(ii(ii==0;0;arr[ii]
arr[ii]!=!='\0';
'\0';++ii)
intarrlen
arrlen==ii;ii; ++ii)
printf("Length arr[ii]
arr[ii] = toupper(arr[ii]); ////needs
= toupper(arr[ii]); needsctype.h
printf("Lengthofof%s %sisis%d\n",
%d\n",arr,
arr,arrlen);
arrlen); ctype.h
printf("Uppercase %s\n",
printf("Uppercase %s\n", arr); arr);
for
for(ii(ii==0;0;arr[ii]
arr[ii]!=!='\0';
'\0';++ii)
++ii)
ifif(arr[ii] char
charcat[strlen(arr)
cat[strlen(arr)++strlen(two)
strlen(two)++1];
(arr[ii] >= 'a' && arr[ii]<=
>= 'a' && arr[ii] <='z')
'z') 1];
arr[ii] += 'A' - 'a'; strcpy(cat, arr);
strcpy(cat, arr);
arr[ii] += 'A' - 'a';
printf("Uppercase strcat(cat,
strcat(cat,two);
printf("Uppercase%s\n", %s\n",arr);
arr); two);
printf("%s
printf("%s +%s
+ %sisis%s\n",
%s\n",arr,
arr,two,
two,cat);
cat);
char
charcat[100];
cat[100];
for
for (ii =0;0;arr[ii]
(ii = arr[ii]!=!='\0';
'\0';++ii)
++ii)
cat[ii] = arr[ii]; When you use these functions,
cat[ii] = arr[ii]; remember that you are incurring a
for
for (intjjjj==0;0;two[jj]
(int two[jj]!=!='\0';
'\0';++ii,
++ii,++jj)
++jj)
cat[ii] = two[jj]; performance penalty.
cat[ii] = two[jj];
cat[ii]
cat[ii] ='\0';
= '\0';
printf("%s
printf("%s++%s %sisis%s\n",
%s\n",arr, arr,two,
two,cat);
cat); 37
Problem: Encrypt / Decrypt Message

ifif(input ifif(input
(input===='e')
'e')inc
inc==1;1;
(input===='e')
'e')inc
inc==1;1; else
else
elseifif(input
(input===='d')
'd')inc
inc==-1;
-1; elseifif(input
(input===='d')
'd')inc
inc==-1;
-1;
...... char
chars[100];
s[100];
gets(s);
gets(s);
char
charc;c;
while
while((c
((c==getchar())
getchar())!=!='\n')
'\n'){ { int
cc+= intii ii==0;0;
+=inc;
inc; while
while(s[ii]
(s[ii]!=!='\0')
'\0'){ {
putchar(c); s[ii]
putchar(c); s[ii]+=
+=inc;inc;
++ii;
++ii;
}} }}
puts(s);
puts(s);

38
awarded
Problem: Find if you are rusticated.

Given a long string containing names of
students rusticated, find out if you are in it.
awarded
gets(message);
gets(message); ////works
works with
withinput
input string
stringhaving
havingspaces.
spaces.
The following
char students
key[] = need
"THARUNto note: RISHABH
DYANISH"; SINGH GAHARWAR, SHAUN MATHEW,
char key[]
THARUN DYANISH = "THARUN DYANISH";T M, DHRUV HEMANT AGGARWAL,
S, KUMARESAN
enum
enum {SAME,
{SAME,These DIFFERENT}
DIFFERENT} comparison ==DIFFERENT;
ARJUN VIKAS RAMESH. studentscomparison DIFFERENT;
should immediately report to the CCW Chairman.
for
for(int
(intmi
mi==0;0;mi mi<<strlen(message);
strlen(message);++mi) ++mi){ {
int
intki;
ki;
for
for (intkiki==0;0;kiki<<strlen(key)
(int strlen(key)&& &&mi
mi++kiki<<strlen(message);
strlen(message);++ki)
++ki)
ifif(message[mi + ki] != key[ki]) break;
(message[mi + ki] != key[ki]) break;
ifif(ki
(ki==
==strlen(key))
strlen(key)){ { When
Whenyouyouaccess
accessarray[index],
array[index],
comparison
comparison==SAME;
SAME; check
check if index is <array
if index is < arraylength.
length.
break;
break;
}} Extend it for
- case insensitive comparison
}} - allowing arbitrary spaces
ifif(comparison
(comparison== ==SAME)
SAME) - similar sounding words “Tarun Danish“
printf("The
printf("The student%s
student %sisisawarded.\n",
awarded.\n",key);
key); if (strstr(message, key))
else
else printf(“Awarded“); 39
printf("No action is required for %s\n", key);
printf("No action is required for %s\n", key); else printf(“No action“);
Week Problems Tools

✓ 0 Solve equations, find weighted sum. Data types, expressions, assignments

✓ 1 Find max, convert marks to grade. Conditionals, logical expressions

✓ 2 Find weighted sum for all students. Loops

✓ 3 Encrypt and decrypt a secret message. Character arrays

4 Our first game: Tic-tac-toe ✓2D arrays


5 Making game modular, reuse. Functions

6 Find Hemachandra/Fibonacci numbers. Recursion

7 Encrypt and decrypt many messages. Dynamic memory, pointers

8 Maintain student records. Aggregate data types

9 Search and sort student records. Searching and sorting algorithms

A Reduce memory wastage. Linked lists

B Implement token system in banks. Queues

C IRCTC-like ticket booking system File handling


40
D Putting it all together All the above

You might also like