Module4 ITC
Module4 ITC
Module4 ITC
m
rows) and second index indicates the ‘column size’( the number of columns).
Ex: int a[10][10]; //Two-dimensional array
co
int b[3][4][5]; //Three-dimensional array
Declaration of Two-dimensional arrays
As we declare the variables before they are used in a program, an array must
e.
also be declared before it is used using the following syntax.
data_type array_name [row_size][col_size];
Syntax:
dg
m
elements of the array during initialization.
Syntax
co
e.
data_type: It can be int, float, char etc.
array_name: It is the name of the array.
dg
This means that after the last character, a null character ('\0') is stored to signify the end of the
character array.
For example, if we write char str[] = "HELLO";
we are declaring an array that has five characters, namely, H, E, L, L, and O. Apart from these characters,
a null character ('\0') is stored at the end of the string. So, the internal representation of the string becomes
ue
HELLO'\0'. To store a string of length 5, we need 5 + 1 locations (1 extra for the null character). The
name of the character array (or the string) is a pointer to the beginning of the string.
Figure 4.1 shows the difference between character storage and string storage.
vt
m
co
e.
dg
ue
vt
ASCII code of a character is stored in the memory and not the character itself. So, at address 1000, 72
will be stored as the ASCII code for H is 72. The statement char str[] = "HELLO";
Syntax:
the general form of declaring a string is
char str[size];
The other way to initialize a string is to initialize it as an array of characters. For example,
char str[] = {'H', 'E', 'L', 'L', 'O', '\0'};
Here, the compiler will automatically calculate the size based on the number of characters.
We can also declare a string with size much larger than the number of elements that are initialized.
For example, consider the statement below.
char str [10] = "HELLO";
In such cases, the compiler creates an array of size 10; stores "HELLO" in it and finally terminates
m
the string with a null character. Rest of the elements in the array are automatically initialized to NULL
Now consider the following statements:
char str[3];
str = "HELLO";
The above initialization statement is illegal in C and would generate a compile-time error.
co
4.1.1 Reading Strings
If we declare a string by writing char str[100]; Then str can be read by the user in three ways:
1. using scanf function,
2. using gets() function, and
e.
3. using getchar(),getch()or getche() function repeatedly.
using scanf()
Strings can be read using scanf() by writing scanf("%s", str);
dg
Unlike int, float, and char values, %s format does not require the ampersand before the variable str.
The main pitfall of using this function is that the function terminates as soon as it finds a blank
space. Therefore we cannot read the complete sentence using scanf() function.
using gets()
The string can be read by writing gets(str);
ue
gets() is a simple function that overcomes the drawbacks of the scanf() function.
gets() function is used to read a sequence of characters (string) with spaces in between.
The ‘gets()’ function allows us to read an ‘entire line’ of input including whitespace characters.
The gets() function takes the starting address of the string which will hold the input.
The string inputted using gets() is automatically terminated with a null character.
vt
using getchar()
Strings can also be read by calling the getchar() function repeatedly to read a sequence of single
characters (unless a terminating character is entered) and simultaneously storing it in a character
array as shown below:
i=0;
ch = getchar;// Get a character
while(ch != '*')
{
str[i] = ch;// Store the read character in str
i++;
ch = getchar();// Get another character
}
str[i] = '\0';// Terminate str with null character
4.1.2 Writing Strings
Strings can be displayed on the screen using the following three ways:
1. using printf() function
2. using puts() function, and
3. using putchar() function repeatedly.
using printf()
Strings can be displayed using printf() by writing printf("%s", str);
We use the format specifier %s to output a string. Observe carefully that there is no ‘&’ character
used with the string variable.
m
We may also use width and precision specifications along with %s.
The precision specifies the maximum number of characters to be displayed, after which the string is
truncated. For example, printf ("%5.3s", str); The above statement would print only the first three
characters in a total field of five characters. Also these characters would be right justified in the
co
allocated width.
To make the string left justified, we must use a minus sign. For example, printf ("%–5.3s", str);
using puts()
A string can be displayed by writing puts(str);
e.
puts() is a simple function that overcomes the drawbacks of the printf() function.
The puts() function writes a line of output on the screen. It terminates the line with a newline
character (‘\n’).
dg
using putchar()
Strings can also be written by calling the putchar() function repeatedly to print a sequence of
single characters.
i=0;
while(str[i] != '\0')
ue
{
putchar(str[i]);// Print the character on the screen
i++;
}
vt
(Scanf(“%[^aeiou]”,str);
Str will accept characters other than those specified in scanset.
Sscanf() : function accepts a string from which to read input.it accepts a template string and
series of related arguments.
Sscanf(const char *str,const char*format,[p1,p2…..]);
m
4.2.1 Fixed-length strings
When storing a string in a fixed-length format, you need to specify an appropriate size for the string
variable. If the size is too small, then you will not be able to store all the elements in the string. On
co
the other hand, if the string size is large, then unnecessarily memory space will be wasted.
e.
dg
ue
vt
4.2.2 Variable-length strings
A better option is to use a variable length format in which the string can be expanded or contracted
to accommodate the elements in it. For example, if you declare a string variable to store the name of
a student. If a student has a long name of say 20 characters, then the string can be expanded to
accommodate 20 characters. On the other hand, a student name has only 5 characters, then the string
variable can be contracted to store only 5 characters. However, to use a variable-length string format
you need a technique to indicate the end of elements that are a part of the string. This can be done
either by using length-controlled string or a delimiter.
1. Length-controlled strings: In a length-controlled string, you need to specify the number of
characters in the string.
2. Delimited strings: In this format, the string is ended with a delimiter such as comma, semicolon,
m
colon, dash, null character etc. The delimiter is then used to identify the end of the string.
co
e.
dg
The number of characters in a string constitutes the length of the string. For example,
LENGTH("C PROGRAMMING IS FUN") will return 20. Note that even blank spaces are counted as
characters in the string.
Figure 4.3 shows an algorithm that calculates the length of a string. In this algorithm, I is used as an
index for traversing string STR. To traverse each and every character of STR, we increment the value
vt
of I. Once we encounter the null character, the control jumps out of the while loop and the length is
initialized with the value of I.
2. Converting Characters of a String into Upper Case
We have already discussed that in the memory ASCII codes are stored instead of the real values. The
ASCII code for A–Z varies from 65 to 91 and the ASCII code for a–z ranges from 97 to 123. So,
if we have to convert a lower case character into uppercase, we just need to subtract 32 from the
ASCII value of the character.
Figure 4.4 shows an algorithm that converts the lower case characters of a string into upper case. In
the algorithm, we initialize I to zero. Using I as the index of STR, we traverse each character of STR
from Step 2 to 3. If the character is in lower case, then it is converted into upper case by subtracting
32 from its ASCII value. But if the character is already in upper case, then it is copied into the
UPPERSTR string. Finally, when all the characters have been traversed, a null character is appended
to UPPERSTR (as done in Step 4).
m
co
e.
3. Converting Characters of a String into Lower Case
If we have to convert an upper case character into lower case, we need to add 32 to the ASCII
value of the character.
dg
Figure 13.8 shows an algorithm that converts the upper case characters of a string into lower case.
In the algorithm, we initialize I to zero. Using I as the index of STR, we traverse each character of
STR from Step 2 to 3. If the character is in upper case, then it is converted into lower case by adding
32 to its ASCII value. But if the character is already in lower case, then it is copied into the Lowerstr
string. Finally, when all the characters have been traversed, a null character is appended to Lowerstr
(as done in Step 4).
ue
vt
m
co
5. Appending a String to Another String
Appending one string to another string involves copying the contents of the source string at the
end of the destination string.
For example, if S1 and S2 are two strings, then appending S1 to S2 means we have to add the contents
of S1 to S2. So, S1 is the source string and S2 is the destination string. The appending operation
would leave the source string S1 unchanged and the destination string S2 = S2 + S1.
e.
Figure 4.5 shows an algorithm that appends two strings. In this algorithm, we first traverse through
the destination string to reach its end, i.e., reach the position where a null character is encountered.
The characters of the source string are then copied into the destination string starting from that
position. Finally, a null character is added to terminate the destination string
dg
ue
vt
m
co
e.
7. Reversing a String
If S1="HELLO", then reverse of S1="OLLEH". To reverse a string, we just need to swap the first
character with the last, second character with the second last character, and so on.
Figure 4.7 shows an algorithm that reverses a string.
dg
In Step 1, I is initialized to zero and J is initialized to the length of the string-1. In Step 2, while loop
is executed until all the characters of the string are accessed. In Step 3, we swap the i th character of
STR with its jth character. In Step 4, the value of I is incremented and J is decremented to traverse
STR in the forward and backward direction respectively.
ue
vt
m
For example, if S1= “Hello World” and we have to copy 7 characters starting from the right then we
have to actually start extracting characters from the 4th position. This is calculated by total number o
characters - n.
For example, if S1= “Hello World”, then Substr_Right(S1, 7) = o World
Figure 13.14 shows an algorithm that extracts n characters from the right of a string.
co
Step 1: [INITIALIZE] SET I = 0, J = Length(STR)-N
Step 2: Repeat Step 3 to 4 while STR[J] != NULL
Step 3: SET Substr[I] = STR[J]
Step 4: SET I = I+1, J=J+1
[END OF LOOP]
Step 5: SET Substr[I] = NULL
e.
Step 6: EXIT
Figure 13.14 Algorithm to extract n characters from the right of a string
In Step 1, we initialize the index variable I to zero and J to Length (STR)-N so that J points to the
dg
character from which the string has to be copied in the substring. In Step 2, a while loop is executed
until the null character in STR is accessed. In Step 3, the Jth character of STR is copied in the Ith
character of Substr. In Step 4, the value of I and J are incremented. In Step 5, Substr is appended with
a null character.
string, the position of the first character of the substring in the given string and the number of
characters/length of the substring.
For example, if we have a string,
str[] = “Welcome to the world of programming”
then
vt
m
substring into NEW_STR. Otherwise, the contents of the text are copied into it.
12. Indexing
This operation returns the position in the string where the string pattern first occurs.
co
For example, INDEX("Welcome to the world of programming", "world") = 15
However, if the pattern does not exist in the string, the INDEX function returns 0.
void main()
{
char str1[10], str2[10]= “JAIN”;
strcpy(str1,str2);
printf(“The Source String=%s\n The Destination String=%s”, str1,str2);
}
Output:
The Source String= JAIN
The Destination String= JAIN
m
Syntax : char *strncpy(char *str1, const char *str2, size_t n);
Where,
str1: it is the destination string.
str2: it is the source string.
n: n is the number of characters to be copied into destination string.
co
Ex: Write a C program to demonstrate the usage of strncpy().
#include<stdio.h>
#include<string.h>
void main()
{
e.
char str1[10], str2[10]= “Computer”;
strncpy(str1,str2,3);
printf (“The Source String=%s\n The Destination String=%s”, str1,str2);
dg
}
Output:
The Source String= Computer
The Destination String= Com
m
Ex: Write a C program to demonstrate the usage of strncat().
#include<stdio.h>
#include<string.h>
void main()
{
co
char str1[15]= “Good”;
char str2[15]= “Morning”;
strncat(str1,str2,4);
printf(“The concatenated String=%s”,str1);
}
Output:
e.
The concatenated String=GoodMorn.
The comparison starts with first character of each string. The comparison continues till the
corresponding characters differ or until the end of the character is reached.
The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
2. If str1 is greater than str2, a positive value is returned.
3. If str1 is less than str2, then the function returns a negative value.
ue
Ex:
“car” and “cat” are different strings. The characters ‘r’ and ‘t’ have different ASCII values. It returns
negative value since ASCII value of ‘r’ is less than the ASCII value of ‘t’.
“car” and “car” are same, the function returns 0.
“cat” and “car” are different strings. The characters ‘t’ and ‘r’ have different ASCII values. It returns
positive value since ASCII value of ‘t’ is greater than the ASCII value of ‘r’.
m
Ex: Write a C program to demonstrate the usage of strcmp().
co
#include<stdio.h>
#include<string.h>
void main()
{
char str1[10]=”Hello”;
char str2[10]=”Hey”;
e.
if(strcmp(str1,str2)==0)
printf(“The two strings are identical”);
else
printf(“The two strings are not identical”);
dg
}
Output:
The two strings are not identical
ue
Syntax: int strcmp(const char *str1, const char *str2, size_t n);
Where,
str1: It is the first string.
str2: It is the second string.
n: It is the number of characters to be compared.
m
8. strchr()
It takes a string and a character as input and finds out the first occurrence of the given character in the
co
string pointed to by the argument str.
It will return the pointer to the first occurrence of that character; if found otherwise, return Null.
Syntax:
char *strchr(const char *str, int c);
e.
Ex: Write a C program to demonstrate the usage of strchr().
#include <stdio.h>
#include <string.h>
dg
void main()
{
char string1[30] = "I love to write.";
char *pos;
pos= strchr(string1, 'w');
if(pos)
ue
9. strrchr()
It takes a string and a character as input and finds out the last occurrence of a given character in that
string.
It will return the pointer to the last occurrence of that character if found otherwise, return Null.
Syntax:
char *strrchr(const char *str, int c);
m
The last position of n is 13.
10. strspn()
The function returns the index of the first character in str1 that dosen’t match any character in str2.
co
Syntax:
size_t strspn( const char *str1, const char *str2 );
11. strcspn()
The function returns the index of the first character in str1 that matches any of the characters in str2.
Syntax:
size_t strcspn( const char *str1, const char *str2);
vt
Syntax:
char *strpbrk( const char *str1, const char *str2 );
m
void main()
{
char str1[] = “PROGRAMMING IN C";
char str2[]=“AB”;
char *ptr = strpbrk(str1,str2);
co
if(ptr== NULL)
printf(“\n No character matches in the two strings”);
else
printf(“\n character in str2 matches with that in str1”);
}
Output:
e.
character in str2 matches with that in str1
dg
13. strtok()
The strtok() function is used to isolate sequential tokens in a null –terminated string, str.
It returns a pointer to the beginning of each subsequent token in the string, after replacing the token
itself with a null character.
When all tokens are left , a null pointer is returned.
ue
Syntax:
char *strtok(char *str1, const char *delimiter);
void main()
{
char str[] = "Hello, to, the, World of, Programming";
char delim[] =",";
char *result;
result = strtok(str,delim);
while(result!= NULL)
{
printf(“\n %s", result);
result = strtok(NULL,delim);
}
}
Output:
Hello
to
the
World of
Programming
m
numeric character.
It stores the address of the first invalid character in str in *end.
You may pass NULL instead of *end if you do not want to store any invalid characters anywhere.
Third argument base specifies whether the number is Hexadecimal, binary, octal or decimal
representation.
co
Syntax:
long strtol( const char *str, char **end, int base );
27418
181
687284
2. strtod()
The function accepts a string str that has an optional plus(‘+’) or minus sign(‘-’) followed by either:
A decimal number containing a sequence of decimal digits optionally consisting of a decimal point, or
A Hexadecimal number consisting of a “OX” or “Ox” followed by a sequence of hexadecimal digits
optionally containing a decimal point.
In both the cases the number should be optionally followed by an exponent (‘E’ or ‘e’ for decimal
constants and ‘P’ or ‘p’ for hexadecimal constants).
Syntax:
double strtod( const char *str, char **end );
m
Output:
123.345000
3. atoi()
The atoi() function converts a given string passed to it as an argument into an integer.
co
The function returns that integer to the calling function.
However, the string should start with a number.
The function will stop reading from the string as soon as it encounters a non-numerical character.
Syntax:
int atoi(const char *str);
e.
Example:
i = atoi(“123.456”);
dg
Result: i=123.
4. atof()
This function converts the string that it accepts as an argument into a double value and then returns
that to the calling function.
The string can be terminated with any non-numerical character other than “E” or “e”.
ue
Syntax:
double atof(const char *str);
Example:
x = atof(“12.39 is the answer”);
Result: x=12.39
vt
5. atol()
This function converts the string into a long int value.
This function will read from the string until it finds any character that should not be in long.
Syntax:
long atol(const char *str);
Example:
x= atol(“12345.6789”);
Result: x = 12345L.
4.4 Arrays of Strings
An array of strings is declared as
<data_type> <array_name> [row_size][column_size];
Here, the first index row_size will specify how many strings are needed and the second index
column_size will specify the length of every individual string.
Ex: char names[20][30];
So here, we will allocate space for 20 names where each name can be a maximum 30 characters long.
Let us see the memory representation of an array of strings. If we have an array declared as char
name[5][10] = {"Ram", "Mohan", "Shyam", "Hari", "Gopal"};
Then in the memory, the array will be stored as shown in Fig. 4.13.
m
co
By declaring the array names, we allocate 50 bytes. But the actual memory occupied is 27 bytes.
Thus, we see that about half of the memory allocated is wasted.
e.
Figure 4.14 shows an algorithm to process individual string from an array of strings. In Step 1, we
initialize the index variable I to zero. In Step 2, a while loop is executed until all the strings in the
array are accessed. In Step 3, each individual string is processed.
dg
ue
Ex: Write a C Program to Read and Print the Names of N Students of a Class.
#include<stdio.h>
void main()
{
char names[5][10];
vt
int i, n;
printf(“\n Enter the number of students : “);
scanf(“%d”, &n);
printf(“\n Enter the names of students :”);
for(i=0;i<n;i++)
{
scanf(“%s”,names[i]);
}
printf(“\n Names of the students are : \n”);
for(i=0;i<n;i++)
puts(names[i]);
}
Example: Write a C program to find the length of string without using strlen() function.
#include<stdio.h>
#include<string.h>
void main()
{
char str[ ];
int count=0; Output:
printf(“Enter the string\n”); Enter the string
gets(str); Good morning
for(i=0;str[i]!=’\0’;i++) Length of the string is=12
{
m
count=count+1;
}
printf(“Length of the string is=%d\n”, count);
}
co
Example: Write a C program to copy string without using strcpy() function.
#include<stdio.h>
#include<string.h>
void main()
{
char src[100],dest[100];
e.
int i; Output:
printf(“Enter the string\n”); Enter the string
gets(str); rahul
for(i=0; str1[i]!=’\0’; i++)
dg
copied string is= rahul
{
str2[i] = str1[i];
}
str2[i]=’\0’;
printf(“copied string is=%d\n”, str2);
}
ue
Syntax
strncpy(dest,src,n);
vt
Where,
dest: it is the destination string.
src: it is the source string.
n: n is the number of characters to be copied into destination string.
‘strncpy()’ function is used to copy ‘n’ characters from the source string src to the destination
string dest.
src C CO O M M P PU UT TE E Rr R \0/ \0
0 1 2 3 4 5 6 7 8 9
m
C CO OM M
dest
0 1 2 3 4 5 6 7 8 9
Example: Write a C program to demonstrate string concatenation without using strcat().
co
#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”, s3[20];
e.
int k,i;
for (i=0; s1[i]!=’\0’; i++)
{
dg
s3[i] = s1[i];
k = k +1;
}
for (i=0; s2[i]!=’\0’; i++)
{
s3[i] = s2[i];
k = k +1;
ue
}
s3[k] = ‘\0’;
printf(“The concatenated String=%s”,s3);
}
vt
Syntax strncat(s1,s2,n);
Where,
s1: It is the first string
s2: It is the second string
n: It is the number of characters of string s2 to be concatenated.
The ‘strncat()’ function is used to concatenate or join n characters of string s2 to the end of string s1.
Example: Write a C program to demonstrate the usage of strncat().
#include<stdio.h>
#include<string.h>
void main()
{
char s1[15]= “Good”;
char s2[15]= “Morning”;
strncat(str1,str2,4);
printf(“The concatenated String=%s”,str1);
}
Output: The concatenated String=GoodMorn.
m
s1
G o o d \0
0 1 2 3 4 5
6 7 8 9 10 12 13 14
s2
co
0 M o r n i n g \0 1 2 3
4 5 6 7 8 9 10 11 12 13 14
s1
G o o d M o r n \0
0 1
e. 2 3 4 5
6 7 8 9 10 12 13 14
dg
6. strcmp(s1,s2): String Compare
Syntax
strcmp(s1,s2);
Where,
s1: It is the first string.
ue
s2 C CA AT R\0 /0
strcmp(s1,s2);
“car” and “cat” are different strings. The characters ‘r’ and ‘t’ have different ASCII values. It returns negative
value since ASCII value of ‘r’ is less than the ASCII value of ‘t’.
m
2.
s1 C
A AR \0
T /0
s2
co
C C
A AR \0/
T /0
strcmp(s1,s2);
Since both the strings are same, the function returns 0.
char s2[10]=”Hey”;
if(strcmp(s1,s2)==0)
printf(“The two strings are identical”);
else
printf(“The two strings are not identical”);
}
ue
{ int i;
char s1[10]=”Hello”;
char s2[10]=”Hey”;
len1 = strlen(s1);
len2 = strlen(s2);
if (strlen(s1) != strlen(s2))
printf(“The two strings are different”);
else{
for (i=0; s1[i]!=’\0’; i++)
{
if(s1[i]!=s2[i])
printf(“strings are different”);
break;
}
}
printf(“The two strings are identical”);
}
Syntax strncmp(s1,s2,n);
Where,
s1: It is the first string.
s2: It is the second string.
n: It is the number of characters to be compared.
This function is used to compare first n number of characters in two strings.
m
The comparison starts with first character of each string. The comparison continues till the corresponding
characters differ or until the end of the character is reached or specified numbers of characters have been tested.
The following values are returned after comparison:
1. If two strings are equal, the function returns 0.
co
2. If s1 is greater than s2, a positive value is returned.
3. If s1 is less than s2, then the function returns a negative value.
Example: Write a C program to demonstrate the usage of strcmp().
#include<stdio.h>
#include<string.h>
void main()
e.
{
char s1[10]=”Hello”;
char s2[10]=”Hey”;
if(strcmp(s1,s2,2)==0)
dg
m
If j doesn’t match with any of elements, return -1 or element not found in an arr[].
co
Example: C Program to search the ‘key’ element in an array using linear search algorithm.
#include <stdio.h>
void main()
{
e.
int array[100], key, i, n;
scanf("%d", &key); 25
35
for (i = 0; i < n; i++) 30
{ 56
if (array[i] == key) Enter a number to search:
{ 30
vt
2. Binary Search:
Binary search is a fast searching algorithm. This search algorithm works on the principle of divide and conquers.
Binary search works on sorted arrays. Binary search begins by comparing the middle element of the array with
the target value. If the target value matches the middle element, its position in the array is returned. If the target
value is less than the middle element, the search continues in the lower half of the array. If the target value is
greater than the middle element, the search continues in the upper half of the array.
m
mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.
co
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find that the value at
e.
location 4 is 27, which is not a match. As the value is greater than 27 and we have a sorted array, so we also know
that the target value must be in the upper portion of the array.
dg
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
ue
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
vt
The value stored at location 7 is not a match; rather it is more than what we are looking for. So, the value must be
in the lower part from this location.
m
Binary search halves the searchable items and thus reduces the count of comparisons to be made to very less
numbers.
Example: C Program to search key elements in array using binary search algorithms.
co
#include<stdio.h>
void main()
{
int n, i, arr[50], key, first, last, middle;
Output:
printf("Enter total number of elements :");
Enter number of
scanf("%d",&n);
printf("Enter array elements:\n");
e. elements in array:
5
for (i=0; i<n; i++)
Enter elements of array
{
10
scanf("%d",&arr[i]);
25
dg
}
35
printf("Enter a number to find :");
50
scanf("%d", &key);
65
first = 0;
Enter a number to
last = n-1;
search:
while (first <= last)
65
ue
{ middle = (first+last)/2;
65 is present at location 5
if ( arr[middle] == key)
{
printf("%d found at location %d\n", key, middle+1);
break;
}
vt
Sorting Algorithms
A sorting algorithm is an algorithm that puts/arrange the elements of a list in a certain order. Order may be
numerical (increasing/decreasing) or alphabetical form. Here we have two different sorting algorithms.
1. Selection sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in
which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end.
m
Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element
becomes a part of the sorted array.
co
This process continues moving unsorted array boundary by one element to the right. This algorithm is not suitable
for large data sets.
How Selection Sort Works?
e.
Consider the following depicted array as an example.
dg
For the first position in the sorted list, the whole list is scanned sequentially. The first position where 14 is stored
presently, we search the whole list and find that 10 is the lowest value.
e the minimum value in the list, appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear manner.
vt
We find that 14 is the second lowest value in the list and it should appear at the second place. We swap these
values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array. Following is a pictorial depiction of the entire
sorting process –
m
co
e.
dg
ue
Example: C Program to sort given array elements using selection sort algorithm.
#include<stdio.h>
vt
int main()
{
int i, j, n, temp, a[25],min;
m
for(i=0;i<n;i++)
printf(" %d",a[i]);
}
2. Bubble Sort.
co
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if
they are in wrong order.
Bubble sort algorithm starts by comparing the first two elements of an array and swapping if necessary, i.e.,
if you want to sort the elements of array in ascending order and if the first element is greater than second
then, you need to swap the elements but, if the first element is smaller than second, you mustn't swap the
e.
element.
Then, again second and third elements are compared and swapped if it is necessary and this process go on
until last and second last element is compared and swapped. This completes the first step of bubble sort.
dg
If there are n elements to be sorted then, the process mentioned above should be repeated n-1 times to get
required result. But, for better performance, in second step, last and second last elements are not compared
because; the proper element is automatically placed at last after first step. Similarly, in third step, last and
second last and second last and third last elements are not compared and so on.
ue
vt
Example: C Program to sort the given array elements using Bubble sort Algorithm.
#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: ");
scanf("%d",&n); Output:
Enter the size of array:
printf("Enter the array elements: ");
5
for(i=0;i<n;++i) Enter elements of array
30
scanf("%d",&a[i]);
25
for(i=1;i<n;++i) 35
10
m
for(j=0;j<(n-i);++j)
56
if(a[j]>a[j+1]) Sorted elements:
10
{
25
co
temp=a[j]; 30
35
a[j]=a[j+1];
56
a[j+1]=temp;
}
e.
printf("\nArray after sorting: ");
for(i=0;i<n;++i)
printf("%d ",a[i]);
dg
}
ue
vt
vt
ue
dg
e.
co
m