KEMBAR78
L16-L19-Searching&Sorting&string123.pptx
Searching Techniques-L16
06/10/2025 CSE 1001 Department of CSE 2
Objectives
To learn and appreciate the following concepts
Searching Technique
 Linear Search
 Binary Search
06/10/2025 CSE 1001 Department of CSE 3
Session outcome
• At the end of session student will be able to understand
• Searching Techniques
06/10/2025 CSE 1001 Department of CSE 4
Arrays – A recap
1D Array:
Syntax: type array_name[size];
 Initialization:
type array-name [size]={list of values}
 Read: Write:
for(i=0;i<n;i++) for(i=0;i<n;i++)
scanf(“%d”,&a[i]); printf(“%d”,a[i]);
06/10/2025 CSE 1001 Department of CSE 5
Searching
•Finding whether a data item is present in a set of
items
→ linear search / sequential search
06/10/2025 CSE 1001 Department of CSE 6
Linear search- illustration 1
06/10/2025 CSE 1001 Department of CSE 7
Linear search- illustration 2
06/10/2025 CSE 1001 Department of CSE 8
int found=0; //setting flag
Print "enter no of numbers";
Input n;
for(i=0;i<n;i++){
Print “enter numbern";
Input a[i]; // entered data items
}
Print “enter the element to be
searched";
Input key; // data to be searched
Pseudo code for linear search
/*search procedure*/
for(i=0; i<n; i++) {
if(a[ i ]==key) // comparison
{
found=1;
pos=i+1;
break;
} }
if(found==1)
Print“data_found_in”,pos,
"position";
otherwise
Print “data is not found“;
Binary Search
06/10/2025 CS&E Dept 9
Binary Search – example-1
06/10/2025 CS&E Dept 10
Binary Search – example-1
06/10/2025 CS&E Dept 11
Binary Search – example-2
06/10/2025 CS&E Dept 12
Binary Search – example-2
06/10/2025 CS&E Dept 13
Binary Search – example-3
06/10/2025 CS&E Dept 14
Binary Search – example-3
06/10/2025 CS&E Dept 15
Binary Search – procedure
06/10/2025 CS&E Dept 16
/* Binary search on sorted array */
low=0;
high=N-1;
do
{
mid= (low + high) / 2;
if ( key < array[mid] )
high = mid - 1;
else if ( key > array[mid])
low = mid + 1;
if( key == array[mid] )
{
printf("SUCCESSFUL SEARCHn");
}
else
{
printf(“Search is FAILEDn");
}
Linear versus Binary Search
06/10/2025 CS&E Dept 17
06/10/2025 CSE 1001 Department of CSE 18
Sorting Techniques
L17-L18
06/10/2025 CSE 1001 Department of CSE 19
Objectives
To learn and appreciate the following concepts
Sorting Technique
 Bubble Sort
 Selection Sort
 Quick Sort
 Merge Sort
06/10/2025 CSE 1001 Department of CSE 20
Sorting
Arrangement of data elements in a particular order
 Bubble sorting
06/10/2025 CSE 1001 Department of CSE 21
Bubble Sort- Illustration
06/10/2025 CSE 1001 Department of CSE 22
Bubble Sort- Illustration
06/10/2025 CSE 1001 Department of CSE 23
for(i=0;i<n;i++)
Input a[i]; // entered elements
for(i=0;i<n-1;i++) //pass
{ for(j=0;j<n-i-1;j++)
{ if(a[j]>a[j+1]) // comparison
{ // interchange
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
Pseudo code for Bubble Sort procedure
Example :
a[ ]={16, 12, 11, 67}
Array after sorting (ascending)
a[ ]={11, 12, 16, 67}
Selection Sort
06/10/2025 CS&E Dept 24
Selection Sort – example-1
06/10/2025 CS&E Dept 25
Selection Sort – example-1
06/10/2025 CS&E Dept 26
Selection Sort – example-1
06/10/2025 CS&E Dept 27
Selection Sort – procedure
06/10/2025 CS&E Dept 28
for(i = 0; i < n-1; i++) // loop for number of pass
{
pos = i; small = a[i];
for(j=i+1; j<n; j++) //loop for searching the smallest
{
if(small > a[j]) // finding the smallest
{ pos = j; // pos for interchanging
small = a[j]; // assigning current small value
}
}
a[pos] = a[i]; //interchanging values
a[i] = small; }
Mergesort
• Split array A[0..n-1] into about equal halves and make copies of
each half in arrays B and C
• Sort arrays B and C recursively
• Merge sorted arrays B and C into array A as follows:
• Repeat the following until no elements remain in one of the arrays:
• compare the first elements in the remaining unprocessed
portions of the arrays
• copy the smaller of the two into A, while incrementing the index
indicating the unprocessed portion of that array
• Once all elements in one of the arrays are processed, copy the
remaining unprocessed elements from the other array into A.
Mergesort Example
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
31
Merge-Sort Tree-Example
7 2  9 4  2 4 7 9
7  2  2 7 9  4  4 9
7  7 2  2 9  9 4  4
32
Execution Example
 Partition
7 2 9 4  3 8 6 1
33
Execution Example (cont.)
 Recursive call, partition
7 2  9 4
7 2 9 4  3 8 6 1
34
Execution Example (cont.)
 Recursive call, partition
7 2  9 4
7  2
7 2 9 4  3 8 6 1
35
Execution Example (cont.)
 Recursive call, base case
7 2  9 4
7  2
7  7
7 2 9 4  3 8 6 1
36
Execution Example (cont.)
 Recursive call, base case
7 2  9 4
7  2
7  7 2  2
7 2 9 4  3 8 6 1
37
Execution Example (cont.)
 Merge
7 2  9 4
7  2  2 7
7  7 2  2
7 2 9 4  3 8 6 1
38
Execution Example (cont.)
 Recursive call, …, base case, merge
7 2  9 4
7  2  2 7 9 4  4 9
7  7 2  2
7 2 9 4  3 8 6 1
9  9 4  4
39
Execution Example (cont.)
 Merge
7 2  9 4  2 4 7 9
7  2  2 7 9 4  4 9
7  7 2  2 9  9 4  4
7 2 9 4  3 8 6 1
40
Execution Example (cont.)
 Recursive call, …, merge, merge
7 2  9 4  2 4 7 9 3 8 6 1  1 3 6 8
7  2  2 7 9 4  4 9 3 8  3 8 6 1  1 6
7  7 2  2 9  9 4  4 3  3 8  8 6  6 1  1
7 2 9 4  3 8 6 1
41
Execution Example (cont.)
 Merge
7 2  9 4  2 4 7 9 3 8 6 1  1 3 6 8
7  2  2 7 9 4  4 9 3 8  3 8 6 1  1 6
7  7 2  2 9  9 4  4 3  3 8  8 6  6 1  1
7 2 9 4  3 8 6 1  1 2 3 4 6 7 8 9
Quicksort
• Select a pivot (partitioning element) – here, the first element
• Rearrange the list so that all the elements in the first s
positions are smaller than or equal to the pivot and all the
elements in the remaining n-s positions are larger than or
equal to the pivot
• Exchange the pivot with the last element in the first (i.e., ) subarray
— the pivot is now in its final position
• Sort the two sub arrays recursively
p
A[i]p A[i]p
Quicksort Example
5 3 1 9 8 2 4 7
2 3 1 4 5 8 9 7
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
06/10/2025 CSE 1001 Department of CSE 45
Comparison between Bubble Sort and Selection Sort
Basis for
Comparison
Bubble Sort Selection Sort
Basic Adjacent element is
compared and then
swapped
Largest element is selected and
swapped with the last element(in
case of ascending order)
Efficiency Inefficient Improved efficiency when
compared to Bubble sort
Method Exchanging selection
Speed Slow Fast when compared to Bubble sort
06/10/2025 CSE 1001 Department of CSE 46
Comparison between Merge Sort and Quick Sort
Basis for Comparison Merge Sort Quick Sort
Number of comparisons Usually performs less number of
comparisons both in worst case
and average case
Requires more number when
compared to merge sort
Memory usage Requires more memory Requires less memory
Method Array is always divided into two
halves
Splitting of the array is not
always divided into two
halves
Speed Consistent on all datasets Fast when the list is small
efficiency efficient Less efficient when
compared to merge sort
06/10/2025 CSE 1001 Department of CSE 47
Tutorials on Sorting and searching
• Write a program in C to implement binary search.
• Write a program in C to sort using merge sort.
• Write a program in C to sort using quick sort by considering first
element of the array as pivot element.
C H A R A C T E R A R R A Y S
S T R I N G S
06/10/2025 CSE 1001 Department of CSE 49
Objectives
To learn and appreciate the following concepts
• Strings definition, declaration, initialization
• Reading Strings
• String Handling Functions
• Programs using strings
• Array of Strings
• Operations on array of strings
06/10/2025 CSE 1001 Department of CSE 50
Session outcome
At the end of session student will be able to
• Declare and initialize strings and array of strings
• Write programs using strings
S t r i n g s
Definition
 A string is an array of characters.
 Any group of characters (except double quote sign) defined between
double quotation marks is a constant string.
 Character strings are often used to build meaningful and readable
programs.
The common operations performed on strings are
Reading and writing strings
Combining strings together
Copying one string to another
Comparing strings to another
Extracting a portion of a string ..etc.
06/10/2025 CSE 1001 Department of CSE 51
S t r i n g s
Declaration and initialization
char string_name[size];
The size determines the number of characters in the string_name.
For example, consider the following array:
char name [20];
is an array that can store up to 20 elements of type char.
It can be represented as:
06/10/2025 CSE 1001 Department of CSE 52
S t r i n g s
The character sequences "Hello" and "Merry Christmas"
represented in an array name respectively are shown as
follows :
06/10/2025 CSE 1001 Department of CSE 53
Initialization of null-terminated character sequences
arrays of characters or strings are ordinary arrays that
follow the same rules of arrays.
For example
To initialize an array of characters with some predetermined
sequence of characters one can initialize like any other array:
char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '0' };
06/10/2025 CSE 1001 Department of CSE 54
Initialization of null-terminated character sequences
 Arrays of char elements have an additional methods to initialize their values:
using string literals
 “Manipal ” is a constant string literal.
For example,
char result[14] =“Manipal”;
 Double quoted (") strings are literal constants whose type is in fact a null-
terminated array of characters.
So string literals enclosed between double quotes always have a null
character ('0') automatically appended at the end.
06/10/2025 CSE 1001 Department of CSE 55
Initialization
 Initialization:
char myWord [ ] = { 'H', 'e', 'l', 'l', 'o', '0' };
char myWord [ ] = "Hello";
 In both cases the array of characters myword is declared with a size of 6
elements of type char:
The 5 characters that compose the word "Hello" plus a final null
character ('0') which specifies the end of the
sequence and that,
In the second case, when using double quotes (") null character ('0') is
appended automatically.
06/10/2025 CSE 1001 Department of CSE 56
Example
#include <stdio.h>
int main() {
char question[ ] = "Please, enter your first name: ";
char greeting[ ] = "Hello, ";
char yourname [ 80];
scanf(“%s”,question);
printf(“%s”, yourname;)
printf(“%s, %sn”,greetings , yourname );
return 0;
}
06/10/2025 CSE 1001 Department of CSE 57
Example
#include <stdio.h>
int main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
printf( “Enter a string: n”);
scanf(“%s”,str); //put string in str
printf(“%s”,str); //display string from str
return 0;
}
06/10/2025 CSE 1001 Department of CSE 58
Reading Embedded Blanks
To read everything that you enter from the keyboard until the
ENTER key is pressed (including space).
Syntax:
gets(string) ;
06/10/2025
CSE 1001 Department of CSE 59
Example
#include <stdio.h>
int main()
{
const int MAX = 80; //max characters in string
char str[MAX]; //string variable str
printf(“nEnter a string: ”);
gets(str); //put string in str or use gets(str)
printf(“ the string is n“);
puts(str);
return 0;
}
06/10/2025 CSE 1001 Department of CSE 60
Count the number of characters in a string
06/10/2025 CSE 1001 Department of CSE 61
#include <stdio.h>
int main()
{
const int Max = 100;
char sent[Max];
int i=0, count=0;
printf("enter sentence n“);
gets(sent);
puts(sent);
while(sent[i]!='0')
{
count++;
i++;
}
printf(“%d n no of characters = “, count);
return 0;
}
06/10/2025 CSE 1001 Department of CSE 62
Count the number of words in a sentence
#include <stdio.h>
int main()
{
const int MAX = 100;
char sent[MAX];
int i=0,count=1;
printf("enter sentence n“);
gets(sent);
printf("n“);
while(sent[i]!='0')
{
if (sent[i]==' '&& sent[i+1]!=' ')
count++;
i++;
}
printf(“n %d n no. of words = " ,count);
return 0;
}
Reading multiple lines: Example
#include <stdio.h>
int main()
{
const int MAX = 2000;
//max characters in string
char str[MAX];
//string variable str
printf("nEnter a string:n“);
gets(str);
printf("You entered:n“);
printf(“%s”,str);
return 0;
}
06/10/2025 CSE 1001 Department of CSE 63
The function will continue to accept characters until enter key is pressed.
Library functions: String Handling functions (built-in)
• Used to manipulate a given string.
• These functions are part of string.h header file.
strlen ()
 gives the length of the string. E.g. strlen(string)
strcpy ()
 copies one string to other. E.g. strcpy(Dstr1, Sstr2)
strcmp ()
 compares the two strings. E.g. strcmp(str1, str2)
strcat ()
Concatinate the two strings. E.g. strcat(str1, str2)
06/10/2025 CSE 1001 Department of CSE 64
Library function: strlen()
• String length can be obtained by using the following function
n=strlen(string);
• This function counts and returns the number of characters in
a string, where n is an integer variable which receives the
value of the length of the string.
• The argument may be a string constant.
Eg: printf(“%d”,strlen(“Manipal”)); prints out 7.
06/10/2025 CSE 1001 Department of CSE 65
Copies a string using a for loop
#include <stdio.h>
#include<string.h>
int main()
{
char str1[ ] = “Manipal Institute of Technology”;
const int MAX = 80; //size of str2 buffer
char str2[MAX]; //empty string
for(int j=0 ; j<strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = ‘0’; //insert NULL at end
printf(“%sn”,str); //display str2
return 0;
}
06/10/2025 CSE 1001 Department of CSE 66
06/10/2025 CSE 1001 Department of CSE 67
Extracting a character from a string
#include <stdio.h>
#include<string.h>
int main() sent[0] sent[1] sent[2] sent[3] sent[4]
{
const int MAX = 100; o/p
char sent[MAX]; 5 (length of string sent)
int len; I
printf("enter sentence n“); D
gets(sent);
len=strlen(sent);
printf(“%dn”,len);
printf(“%cn”,sent[len-1]);
printf(“%cn”,sent[0]); }
D E L H I
06/10/2025 CSE 1001 Department of CSE 68
To encrypt and decrypt a string
#include <stdio.h>
#include<string.h>
int main()
{
const int MAX = 100;
char sent[MAX];
int len,I;
printf("enter sentence n“);
gets(sent);
for(i=0;sent[i]!=‘0’;i++)
sent[i]=sent[i]+1;
printf(“ the encrypted string is n”);
puts(sent);
for(i=0;sent[i]!=‘0’;i++)
sent[i]=sent[i]-1;
printf(“ the decrypted string is n”);
puts(sent);
}
Library function: strcpy()
Copying a String the EASY WAY using
strcpy(destination, source)
 The strcpy function works almost like a string assignment operator and
assigns the contents of source to destination.
destination may be a character array variable or a string constant.
e.g., strcpy(city, ”DELHI”);
will assign the string “DELHI” to the string variable city.
Similarly, the statement strcpy(city1, city2);
will assign the contents of the string variable city2 to the string variable
city1.
The size of the array city1 should be large enough to receive the
contents of city2.
06/10/2025 CSE 1001 Department of CSE 69
strcpy(): Example
#include <stdio.h>
int main()
{
char str1[ ] = “Tiger, tiger, burning brightn”
“In the forests of the night”;
const int MAX = 80; //size of str2 buffer
char str2[MAX]; //empty string
strcpy(str2, str1); //copy str1 to str2
printf(“%s”,str2);//display str2
}
06/10/2025 CSE 1001 Department of CSE 70
Library function: strcmp()
06/10/2025 CSE 1001 Department of CSE 71
 The strcmp function compares two strings identified by the
arguments and has a value 0 if they are equal.
 If they are not, it has the numeric difference between the first non
matching characters in the strings.
strcmp(string1, string2);
string1 and string2 may be string variables or string constants.
e.g., strcmp(“their”, ”there”); will return a value of –9 which is the
numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus
“r” with respect to ASCII code is –9.
If the value is negative, string1 is alphabetically above string2.
Library function: strcat()
06/10/2025 CSE 1001 Department of CSE 72
The strcat function joins two strings together.
It takes the following form:
strcat(string1, string2);
string1 and string2 are character arrays.
When the function strcat is excuted, string2 is
appended to string1.
 It does so by removing the null character at the end
of string1 and placing string2 from there.
The string at string2 remains unchanged.
Concatenation of 2 strings
06/10/2025 CSE 1001 Department of CSE 73
#include <stdio.h>
#include <string.h>
int main()
{ char s1[40], s2[50];
printf("nEnter the first string“);
gets(s1);
printf("nEnter the second string“);
gets(s2);
strcat(s1, s2);
printf("nConcatenated string is“);
printf(“%s”,s1);
return 0; }
Check whether a string is Palindrome or not
06/10/2025 CSE 1001 Department of CSE 74
int main()
{
char str[30];
int i, j, n, flag=1;
printf("nEnter the string:“);
gets(str);
//find the string length
for(i=0;str[i]!='0';i++);
n=i; //n=strlen(str);
for(i=0;i<n/2;i++)
{
if(str[i]!=str[n-i-1])
{ flag=0;
break; }
}
if(flag==1)
printf("nIts a Palindrome“);
else
printf("nNot a Palindrome“);
return 0;
}
Reversing a string
06/10/2025 CSE 1001 Department of CSE 75
int main()
{
char str[70];
char temp;
int i, n=0;
printf("nEnter the string:“);
gets(str);
for(i=0;str[i]!='0';i++)
n++;
for(i=0;i<n/2;i++)
{
temp=str[i];
str[i]=str[n-i-1];
str[n-i-1]=temp;
}
printf("nReversed string is:“);
puts(str);
return 0;
}
Print an alphabet in decimal [ASCII] & character form
06/10/2025 CSE 1001 Department of CSE 76
int main()
{
char c;
printf("n“);
for(c=65;c<=122;c++)
{
if(c>90 && c<97)
continue;
printf(“%c”, c);
printf(“-”);
printf(“%d”,(int)c);
}
printf("n“);
return 0;
}
Change all lower case letters into uppercase in a
sentence
06/10/2025 CSE 1001 Department of CSE 77
int main()
{
char string[30];
int i,n=0;
printf("nEnter the string“);
gets(string);
for(i=0;string[i]!='0';i++)
n++;
for(i=0;i<n;i++)
{
if(string[i]>=97 && string[i]<=122)
string[i]=string[i]-32;
}
puts(string);
getch();
return 0;
}
Tutorials on Simple Operations on String
• Write a simple C program to retrieve first word from a sentence.
• Write a C program to remove blank space from the string
• Write a C program to count the number of vowels and consonants in a
given string.
06/10/2025 CSE 1001 Department of CSE 78
Summary
• Searching Technique
o Linear Search
o Binary Search
• Sorting Technique
o Bubble Sort
o Selection Sort
o Merge Sort
o Quick Sort
06/10/2025 CSE 1001 Department of CSE 79

L16-L19-Searching&Sorting&string123.pptx

  • 1.
  • 2.
    06/10/2025 CSE 1001Department of CSE 2 Objectives To learn and appreciate the following concepts Searching Technique  Linear Search  Binary Search
  • 3.
    06/10/2025 CSE 1001Department of CSE 3 Session outcome • At the end of session student will be able to understand • Searching Techniques
  • 4.
    06/10/2025 CSE 1001Department of CSE 4 Arrays – A recap 1D Array: Syntax: type array_name[size];  Initialization: type array-name [size]={list of values}  Read: Write: for(i=0;i<n;i++) for(i=0;i<n;i++) scanf(“%d”,&a[i]); printf(“%d”,a[i]);
  • 5.
    06/10/2025 CSE 1001Department of CSE 5 Searching •Finding whether a data item is present in a set of items → linear search / sequential search
  • 6.
    06/10/2025 CSE 1001Department of CSE 6 Linear search- illustration 1
  • 7.
    06/10/2025 CSE 1001Department of CSE 7 Linear search- illustration 2
  • 8.
    06/10/2025 CSE 1001Department of CSE 8 int found=0; //setting flag Print "enter no of numbers"; Input n; for(i=0;i<n;i++){ Print “enter numbern"; Input a[i]; // entered data items } Print “enter the element to be searched"; Input key; // data to be searched Pseudo code for linear search /*search procedure*/ for(i=0; i<n; i++) { if(a[ i ]==key) // comparison { found=1; pos=i+1; break; } } if(found==1) Print“data_found_in”,pos, "position"; otherwise Print “data is not found“;
  • 9.
  • 10.
    Binary Search –example-1 06/10/2025 CS&E Dept 10
  • 11.
    Binary Search –example-1 06/10/2025 CS&E Dept 11
  • 12.
    Binary Search –example-2 06/10/2025 CS&E Dept 12
  • 13.
    Binary Search –example-2 06/10/2025 CS&E Dept 13
  • 14.
    Binary Search –example-3 06/10/2025 CS&E Dept 14
  • 15.
    Binary Search –example-3 06/10/2025 CS&E Dept 15
  • 16.
    Binary Search –procedure 06/10/2025 CS&E Dept 16 /* Binary search on sorted array */ low=0; high=N-1; do { mid= (low + high) / 2; if ( key < array[mid] ) high = mid - 1; else if ( key > array[mid]) low = mid + 1; if( key == array[mid] ) { printf("SUCCESSFUL SEARCHn"); } else { printf(“Search is FAILEDn"); }
  • 17.
    Linear versus BinarySearch 06/10/2025 CS&E Dept 17
  • 18.
    06/10/2025 CSE 1001Department of CSE 18 Sorting Techniques L17-L18
  • 19.
    06/10/2025 CSE 1001Department of CSE 19 Objectives To learn and appreciate the following concepts Sorting Technique  Bubble Sort  Selection Sort  Quick Sort  Merge Sort
  • 20.
    06/10/2025 CSE 1001Department of CSE 20 Sorting Arrangement of data elements in a particular order  Bubble sorting
  • 21.
    06/10/2025 CSE 1001Department of CSE 21 Bubble Sort- Illustration
  • 22.
    06/10/2025 CSE 1001Department of CSE 22 Bubble Sort- Illustration
  • 23.
    06/10/2025 CSE 1001Department of CSE 23 for(i=0;i<n;i++) Input a[i]; // entered elements for(i=0;i<n-1;i++) //pass { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) // comparison { // interchange temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } Pseudo code for Bubble Sort procedure Example : a[ ]={16, 12, 11, 67} Array after sorting (ascending) a[ ]={11, 12, 16, 67}
  • 24.
  • 25.
    Selection Sort –example-1 06/10/2025 CS&E Dept 25
  • 26.
    Selection Sort –example-1 06/10/2025 CS&E Dept 26
  • 27.
    Selection Sort –example-1 06/10/2025 CS&E Dept 27
  • 28.
    Selection Sort –procedure 06/10/2025 CS&E Dept 28 for(i = 0; i < n-1; i++) // loop for number of pass { pos = i; small = a[i]; for(j=i+1; j<n; j++) //loop for searching the smallest { if(small > a[j]) // finding the smallest { pos = j; // pos for interchanging small = a[j]; // assigning current small value } } a[pos] = a[i]; //interchanging values a[i] = small; }
  • 29.
    Mergesort • Split arrayA[0..n-1] into about equal halves and make copies of each half in arrays B and C • Sort arrays B and C recursively • Merge sorted arrays B and C into array A as follows: • Repeat the following until no elements remain in one of the arrays: • compare the first elements in the remaining unprocessed portions of the arrays • copy the smaller of the two into A, while incrementing the index indicating the unprocessed portion of that array • Once all elements in one of the arrays are processed, copy the remaining unprocessed elements from the other array into A.
  • 30.
    Mergesort Example 8 32 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 3 8 2 9 1 7 4 5 2 3 8 9 1 4 5 7 1 2 3 4 5 7 8 9 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 3 8 2 9 1 7 4 5 2 3 8 9 1 4 5 7 1 2 3 4 5 7 8 9 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 8 3 2 9 7 1 5 4 3 8 2 9 1 7 4 5 2 3 8 9 1 4 5 7 1 2 3 4 5 7 8 9
  • 31.
    31 Merge-Sort Tree-Example 7 2 9 4  2 4 7 9 7  2  2 7 9  4  4 9 7  7 2  2 9  9 4  4
  • 32.
  • 33.
    33 Execution Example (cont.) Recursive call, partition 7 2  9 4 7 2 9 4  3 8 6 1
  • 34.
    34 Execution Example (cont.) Recursive call, partition 7 2  9 4 7  2 7 2 9 4  3 8 6 1
  • 35.
    35 Execution Example (cont.) Recursive call, base case 7 2  9 4 7  2 7  7 7 2 9 4  3 8 6 1
  • 36.
    36 Execution Example (cont.) Recursive call, base case 7 2  9 4 7  2 7  7 2  2 7 2 9 4  3 8 6 1
  • 37.
    37 Execution Example (cont.) Merge 7 2  9 4 7  2  2 7 7  7 2  2 7 2 9 4  3 8 6 1
  • 38.
    38 Execution Example (cont.) Recursive call, …, base case, merge 7 2  9 4 7  2  2 7 9 4  4 9 7  7 2  2 7 2 9 4  3 8 6 1 9  9 4  4
  • 39.
    39 Execution Example (cont.) Merge 7 2  9 4  2 4 7 9 7  2  2 7 9 4  4 9 7  7 2  2 9  9 4  4 7 2 9 4  3 8 6 1
  • 40.
    40 Execution Example (cont.) Recursive call, …, merge, merge 7 2  9 4  2 4 7 9 3 8 6 1  1 3 6 8 7  2  2 7 9 4  4 9 3 8  3 8 6 1  1 6 7  7 2  2 9  9 4  4 3  3 8  8 6  6 1  1 7 2 9 4  3 8 6 1
  • 41.
    41 Execution Example (cont.) Merge 7 2  9 4  2 4 7 9 3 8 6 1  1 3 6 8 7  2  2 7 9 4  4 9 3 8  3 8 6 1  1 6 7  7 2  2 9  9 4  4 3  3 8  8 6  6 1  1 7 2 9 4  3 8 6 1  1 2 3 4 6 7 8 9
  • 42.
    Quicksort • Select apivot (partitioning element) – here, the first element • Rearrange the list so that all the elements in the first s positions are smaller than or equal to the pivot and all the elements in the remaining n-s positions are larger than or equal to the pivot • Exchange the pivot with the last element in the first (i.e., ) subarray — the pivot is now in its final position • Sort the two sub arrays recursively p A[i]p A[i]p
  • 44.
    Quicksort Example 5 31 9 8 2 4 7 2 3 1 4 5 8 9 7 1 2 3 4 5 7 8 9 1 2 3 4 5 7 8 9 1 2 3 4 5 7 8 9 1 2 3 4 5 7 8 9
  • 45.
    06/10/2025 CSE 1001Department of CSE 45 Comparison between Bubble Sort and Selection Sort Basis for Comparison Bubble Sort Selection Sort Basic Adjacent element is compared and then swapped Largest element is selected and swapped with the last element(in case of ascending order) Efficiency Inefficient Improved efficiency when compared to Bubble sort Method Exchanging selection Speed Slow Fast when compared to Bubble sort
  • 46.
    06/10/2025 CSE 1001Department of CSE 46 Comparison between Merge Sort and Quick Sort Basis for Comparison Merge Sort Quick Sort Number of comparisons Usually performs less number of comparisons both in worst case and average case Requires more number when compared to merge sort Memory usage Requires more memory Requires less memory Method Array is always divided into two halves Splitting of the array is not always divided into two halves Speed Consistent on all datasets Fast when the list is small efficiency efficient Less efficient when compared to merge sort
  • 47.
    06/10/2025 CSE 1001Department of CSE 47 Tutorials on Sorting and searching • Write a program in C to implement binary search. • Write a program in C to sort using merge sort. • Write a program in C to sort using quick sort by considering first element of the array as pivot element.
  • 48.
    C H AR A C T E R A R R A Y S S T R I N G S
  • 49.
    06/10/2025 CSE 1001Department of CSE 49 Objectives To learn and appreciate the following concepts • Strings definition, declaration, initialization • Reading Strings • String Handling Functions • Programs using strings • Array of Strings • Operations on array of strings
  • 50.
    06/10/2025 CSE 1001Department of CSE 50 Session outcome At the end of session student will be able to • Declare and initialize strings and array of strings • Write programs using strings
  • 51.
    S t ri n g s Definition  A string is an array of characters.  Any group of characters (except double quote sign) defined between double quotation marks is a constant string.  Character strings are often used to build meaningful and readable programs. The common operations performed on strings are Reading and writing strings Combining strings together Copying one string to another Comparing strings to another Extracting a portion of a string ..etc. 06/10/2025 CSE 1001 Department of CSE 51
  • 52.
    S t ri n g s Declaration and initialization char string_name[size]; The size determines the number of characters in the string_name. For example, consider the following array: char name [20]; is an array that can store up to 20 elements of type char. It can be represented as: 06/10/2025 CSE 1001 Department of CSE 52
  • 53.
    S t ri n g s The character sequences "Hello" and "Merry Christmas" represented in an array name respectively are shown as follows : 06/10/2025 CSE 1001 Department of CSE 53
  • 54.
    Initialization of null-terminatedcharacter sequences arrays of characters or strings are ordinary arrays that follow the same rules of arrays. For example To initialize an array of characters with some predetermined sequence of characters one can initialize like any other array: char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '0' }; 06/10/2025 CSE 1001 Department of CSE 54
  • 55.
    Initialization of null-terminatedcharacter sequences  Arrays of char elements have an additional methods to initialize their values: using string literals  “Manipal ” is a constant string literal. For example, char result[14] =“Manipal”;  Double quoted (") strings are literal constants whose type is in fact a null- terminated array of characters. So string literals enclosed between double quotes always have a null character ('0') automatically appended at the end. 06/10/2025 CSE 1001 Department of CSE 55
  • 56.
    Initialization  Initialization: char myWord[ ] = { 'H', 'e', 'l', 'l', 'o', '0' }; char myWord [ ] = "Hello";  In both cases the array of characters myword is declared with a size of 6 elements of type char: The 5 characters that compose the word "Hello" plus a final null character ('0') which specifies the end of the sequence and that, In the second case, when using double quotes (") null character ('0') is appended automatically. 06/10/2025 CSE 1001 Department of CSE 56
  • 57.
    Example #include <stdio.h> int main(){ char question[ ] = "Please, enter your first name: "; char greeting[ ] = "Hello, "; char yourname [ 80]; scanf(“%s”,question); printf(“%s”, yourname;) printf(“%s, %sn”,greetings , yourname ); return 0; } 06/10/2025 CSE 1001 Department of CSE 57
  • 58.
    Example #include <stdio.h> int main() { constint MAX = 80; //max characters in string char str[MAX]; //string variable str printf( “Enter a string: n”); scanf(“%s”,str); //put string in str printf(“%s”,str); //display string from str return 0; } 06/10/2025 CSE 1001 Department of CSE 58
  • 59.
    Reading Embedded Blanks Toread everything that you enter from the keyboard until the ENTER key is pressed (including space). Syntax: gets(string) ; 06/10/2025 CSE 1001 Department of CSE 59
  • 60.
    Example #include <stdio.h> int main() { constint MAX = 80; //max characters in string char str[MAX]; //string variable str printf(“nEnter a string: ”); gets(str); //put string in str or use gets(str) printf(“ the string is n“); puts(str); return 0; } 06/10/2025 CSE 1001 Department of CSE 60
  • 61.
    Count the numberof characters in a string 06/10/2025 CSE 1001 Department of CSE 61 #include <stdio.h> int main() { const int Max = 100; char sent[Max]; int i=0, count=0; printf("enter sentence n“); gets(sent); puts(sent); while(sent[i]!='0') { count++; i++; } printf(“%d n no of characters = “, count); return 0; }
  • 62.
    06/10/2025 CSE 1001Department of CSE 62 Count the number of words in a sentence #include <stdio.h> int main() { const int MAX = 100; char sent[MAX]; int i=0,count=1; printf("enter sentence n“); gets(sent); printf("n“); while(sent[i]!='0') { if (sent[i]==' '&& sent[i+1]!=' ') count++; i++; } printf(“n %d n no. of words = " ,count); return 0; }
  • 63.
    Reading multiple lines:Example #include <stdio.h> int main() { const int MAX = 2000; //max characters in string char str[MAX]; //string variable str printf("nEnter a string:n“); gets(str); printf("You entered:n“); printf(“%s”,str); return 0; } 06/10/2025 CSE 1001 Department of CSE 63 The function will continue to accept characters until enter key is pressed.
  • 64.
    Library functions: StringHandling functions (built-in) • Used to manipulate a given string. • These functions are part of string.h header file. strlen ()  gives the length of the string. E.g. strlen(string) strcpy ()  copies one string to other. E.g. strcpy(Dstr1, Sstr2) strcmp ()  compares the two strings. E.g. strcmp(str1, str2) strcat () Concatinate the two strings. E.g. strcat(str1, str2) 06/10/2025 CSE 1001 Department of CSE 64
  • 65.
    Library function: strlen() •String length can be obtained by using the following function n=strlen(string); • This function counts and returns the number of characters in a string, where n is an integer variable which receives the value of the length of the string. • The argument may be a string constant. Eg: printf(“%d”,strlen(“Manipal”)); prints out 7. 06/10/2025 CSE 1001 Department of CSE 65
  • 66.
    Copies a stringusing a for loop #include <stdio.h> #include<string.h> int main() { char str1[ ] = “Manipal Institute of Technology”; const int MAX = 80; //size of str2 buffer char str2[MAX]; //empty string for(int j=0 ; j<strlen(str1); j++) //copy strlen characters str2[j] = str1[j]; // from str1 to str2 str2[j] = ‘0’; //insert NULL at end printf(“%sn”,str); //display str2 return 0; } 06/10/2025 CSE 1001 Department of CSE 66
  • 67.
    06/10/2025 CSE 1001Department of CSE 67 Extracting a character from a string #include <stdio.h> #include<string.h> int main() sent[0] sent[1] sent[2] sent[3] sent[4] { const int MAX = 100; o/p char sent[MAX]; 5 (length of string sent) int len; I printf("enter sentence n“); D gets(sent); len=strlen(sent); printf(“%dn”,len); printf(“%cn”,sent[len-1]); printf(“%cn”,sent[0]); } D E L H I
  • 68.
    06/10/2025 CSE 1001Department of CSE 68 To encrypt and decrypt a string #include <stdio.h> #include<string.h> int main() { const int MAX = 100; char sent[MAX]; int len,I; printf("enter sentence n“); gets(sent); for(i=0;sent[i]!=‘0’;i++) sent[i]=sent[i]+1; printf(“ the encrypted string is n”); puts(sent); for(i=0;sent[i]!=‘0’;i++) sent[i]=sent[i]-1; printf(“ the decrypted string is n”); puts(sent); }
  • 69.
    Library function: strcpy() Copyinga String the EASY WAY using strcpy(destination, source)  The strcpy function works almost like a string assignment operator and assigns the contents of source to destination. destination may be a character array variable or a string constant. e.g., strcpy(city, ”DELHI”); will assign the string “DELHI” to the string variable city. Similarly, the statement strcpy(city1, city2); will assign the contents of the string variable city2 to the string variable city1. The size of the array city1 should be large enough to receive the contents of city2. 06/10/2025 CSE 1001 Department of CSE 69
  • 70.
    strcpy(): Example #include <stdio.h> intmain() { char str1[ ] = “Tiger, tiger, burning brightn” “In the forests of the night”; const int MAX = 80; //size of str2 buffer char str2[MAX]; //empty string strcpy(str2, str1); //copy str1 to str2 printf(“%s”,str2);//display str2 } 06/10/2025 CSE 1001 Department of CSE 70
  • 71.
    Library function: strcmp() 06/10/2025CSE 1001 Department of CSE 71  The strcmp function compares two strings identified by the arguments and has a value 0 if they are equal.  If they are not, it has the numeric difference between the first non matching characters in the strings. strcmp(string1, string2); string1 and string2 may be string variables or string constants. e.g., strcmp(“their”, ”there”); will return a value of –9 which is the numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus “r” with respect to ASCII code is –9. If the value is negative, string1 is alphabetically above string2.
  • 72.
    Library function: strcat() 06/10/2025CSE 1001 Department of CSE 72 The strcat function joins two strings together. It takes the following form: strcat(string1, string2); string1 and string2 are character arrays. When the function strcat is excuted, string2 is appended to string1.  It does so by removing the null character at the end of string1 and placing string2 from there. The string at string2 remains unchanged.
  • 73.
    Concatenation of 2strings 06/10/2025 CSE 1001 Department of CSE 73 #include <stdio.h> #include <string.h> int main() { char s1[40], s2[50]; printf("nEnter the first string“); gets(s1); printf("nEnter the second string“); gets(s2); strcat(s1, s2); printf("nConcatenated string is“); printf(“%s”,s1); return 0; }
  • 74.
    Check whether astring is Palindrome or not 06/10/2025 CSE 1001 Department of CSE 74 int main() { char str[30]; int i, j, n, flag=1; printf("nEnter the string:“); gets(str); //find the string length for(i=0;str[i]!='0';i++); n=i; //n=strlen(str); for(i=0;i<n/2;i++) { if(str[i]!=str[n-i-1]) { flag=0; break; } } if(flag==1) printf("nIts a Palindrome“); else printf("nNot a Palindrome“); return 0; }
  • 75.
    Reversing a string 06/10/2025CSE 1001 Department of CSE 75 int main() { char str[70]; char temp; int i, n=0; printf("nEnter the string:“); gets(str); for(i=0;str[i]!='0';i++) n++; for(i=0;i<n/2;i++) { temp=str[i]; str[i]=str[n-i-1]; str[n-i-1]=temp; } printf("nReversed string is:“); puts(str); return 0; }
  • 76.
    Print an alphabetin decimal [ASCII] & character form 06/10/2025 CSE 1001 Department of CSE 76 int main() { char c; printf("n“); for(c=65;c<=122;c++) { if(c>90 && c<97) continue; printf(“%c”, c); printf(“-”); printf(“%d”,(int)c); } printf("n“); return 0; }
  • 77.
    Change all lowercase letters into uppercase in a sentence 06/10/2025 CSE 1001 Department of CSE 77 int main() { char string[30]; int i,n=0; printf("nEnter the string“); gets(string); for(i=0;string[i]!='0';i++) n++; for(i=0;i<n;i++) { if(string[i]>=97 && string[i]<=122) string[i]=string[i]-32; } puts(string); getch(); return 0; }
  • 78.
    Tutorials on SimpleOperations on String • Write a simple C program to retrieve first word from a sentence. • Write a C program to remove blank space from the string • Write a C program to count the number of vowels and consonants in a given string. 06/10/2025 CSE 1001 Department of CSE 78
  • 79.
    Summary • Searching Technique oLinear Search o Binary Search • Sorting Technique o Bubble Sort o Selection Sort o Merge Sort o Quick Sort 06/10/2025 CSE 1001 Department of CSE 79

Editor's Notes

  • #5 In computer science, linear search or sequential search is a method for finding a particular value in a list, which consists of checking every one of its elements, one at a time and in sequence, until the desired one is found. Linear search is the simplest search algorithm. classifications: linear search / binary search based on how the search is performed
  • #6 The Linear Search is applied on the set of items that are not arranged in any particular order In linear search , the searching process starts from the first item. The searching is continued till either the item is found or the end of the list is reached indicating that the item is not found. The items in the list are assumed to be unique.
  • #7 The Linear Search is applied on the set of items that are not arranged in any particular order In linear search , the searching process starts from the first item. The searching is continued till either the item is found or the end of the list is reached indicating that the item is not found. The items in the list are assumed to be unique.
  • #18 Bubble sort, sometimes referred to as sinking sort/ripple sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
  • #20 Bubble sort, sometimes referred to as sinking sort/ripple sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
  • #30 Go over this example in detail, then do another example of merging, something like: (1 2 5 7 9) (3 4 6)
  • #51 A new data type , the character string, which is used to represent a sequence of characters regarded as a single data item. In C++ strings of characters are held as an array of characters, one character held in each array element.
  • #52 Syntax for declaration char <array/string name> [max. number of characters to be stored +1]; The number of elements that can be stored in a string is always n-1, if the size of the array specified is n. This is because 1 byte is reserved for the NULL character '\0' i.e. backslash zero. A string is always terminated with the NULL character. Example: char str[80]; In the above example, str can be used to store a string with 79 characters.
  • #54 Because a character is initialized by including it in single-quotes, when creating an array of characters, to initialize it, you must also include each letter accordingly. A name such as James can be initialized as follows: char Name[6] = { 'J', 'a', 'm', 'e', 's' };
  • #56 Initializing a string A string can be initialized to a constant value when it is declared. char str[ ] = "Good";     Or char str[]={'G','o','o','d','\0'}; Here. 'G' will be stored in str[0], 'o' in str[1] and so on. Note: When the value is assigned to the complete string at once, the computer automatically inserts the NULL character at the end of the string. But, if it is done character by character, then we have to insert it at the end of the string.
  • #57  gets() It can be used to take input of a value of any data type. It can be used to take input of a string. It takes the white space i.e. a blank, a tab, or a new line character as a string terminator. It does not take the white space i.e. a blank, a tab, or a new line character, as a string terminator. It requires header file iostream.h It requires the header file stdio.h Example: char S[80]; cout<<"Enter a string:”; cin>>S; Example: char S[80]; cout<<"Enter a string:"; gets(S);
  • #58 cout puts() It can be used to display the value of any data type. It can be used to display the value of a string. It does not take a line feed after displaying the string. It takes a line feed after displaying the string. It requires the header file iostream.h It requires the header file stdio.h Example: char S[80]="Computers"; cout<<S<<S; Output: ComputersComputers Example: char S[80]="Computers"; puts(S); puts(S); Output: Computers Computers
  • #59 Reading strings with/without embedded blanks To read a string without blanks cin can be used cin>>str; To read a string with blanks cin.getline() or gets() can be used. cin.getline(str,80);    -Or- gets(str);
  • #66 Copying a String the Hard Way It is not possible to copy one string to another, by assigning first string to second. For example is s1 and s2 are the 2 strings then: s2=s1; is an invalid statement. The best way to understand the true nature of strings is to deal with them character by character. The following program copies one string to another character by character. The copying is done one character at a time, in the Statement str2[j] = str1[j]; The copied version of the string must be terminated with a null. However, the string length returned by strlen() does not include the null. We could copy one additional character, but it’s safer to insert the null explicitly. We do this with the line str2[j] = ‘\0’; If you don’t insert this character, you’ll find that the string printed by the program includes all sorts of weird characters following the string you want. The << just keeps on printing characters, whatever they are, until by chance it encounters a ‘\0’.