Module 5 - CP - CS100 - Notes - Ktuqbank
Module 5 - CP - CS100 - Notes - Ktuqbank
COM
MODULE 5
Module V
Sorting and Searching : Bubble sort, Selection sort, Linear Search and Binary
search. Scope rules Storage classes. Bit-wise operations.
Bubble sort
Algorithm :
Step 1: [Start]
Begin
Read n
KTUQBANK.COM
Read num[ i ]
End for
Print num[ i]
End for
temp= num[j]
num[j] = num[j + 1]
num[j+1] = temp
End if
End for
End for
Print num[i]
End for
Selection Sort
Consider the following depicted array as an example.
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.
KTUQBANK.COM
So we replace 14 with 10. After one iteration 10, which happens to be 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.
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
Selection sort
2. Loop over the input until it is empty, "removing" the first remaining (leftmost) element.
3. Compare the removed element against the current result, starting from the highest (rightmost)
element, and working left towards the lowest element.
4. If the removed input element is lower than the current result element, copy that value into the
following element to make room for the new element below, and repeat with the next lowest
result element.
5. Otherwise, the new element is in the correct location; save it in the cell left by copying the
last examined result up, and start again from (2) with the next input element.
Algorithm :
Example:
KTUQBANK.COM
Example:
#include <stdio.h>
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
Output:
Element is present at index 3
#include <stdio.h>
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
Output:
Element is present at index 3
Storage class in C decides the part of storage to allocate memory for a variable, it also determines
the scope of a variable. All variables defined in a C program get some physical location in memory
where variable's value is stored. Memory and CPU registers are types of memory locations where a
variable's value can be stored. The storage class of a variable in C determines the life time of the
variable if this is 'global' or 'local'. Along with the life time of a variable, storage class also
determines variable's storage location (memory or registers), the scope (visibility level) of the
variable, and the initial value of the variable. There are four storage classes in C those are
automatic, register, static, and external.
At most one storage class specifier may be given in a declaration. If no storage class specifier is
specified then following rules are used:
1. Variables declared inside a function are taken to be auto.
2. Functions declared within a function are taken to be extern.
3. Variables and functions declared outside a function are taken to be static, with external
linkage.
KTUQBANK.COM
Variables and functions having external linkage are available to all files that constitute a program.
File scope variables and functions declared as static (described shortly) have internal linkage.
These are known only within the file in which they are declared. Local variables have no linkage
and are therefore known only within their own block.
OUTPUT
======
3 2 1
In above example program you see three definitions for variable i. Here, you may be thinking if
there could be more than one variable with the same name. Yes, there could be if these variables are
defined in different blocks. So, there will be no error here and the program will compile and execute
successfully. The printf in the inner most block will print 3 and the variable i defined in the
inner most block gets destroyed as soon as control exits from the block. Now control comes to the
second outer block and prints 2 then comes to the outer block and prints 1. Here, note that automatic
variables must always be initialized properly, otherwise you are likely to get unexpected results
because automatic variables are not given any initial value by the compiler.
the block. A register declaration is equivalent to an auto declaration, but hints that the
declared variable will be accessed frequently; therefore they are placed in CPU registers, not in
memory. Only a few variables are actually placed into registers, and only certain types are eligible;
the restrictions are implementation-dependent. However, if a variable is declared register, the unary
& (address of) operator may not be applied to it, explicitly or implicitly. Register variables are also
given no initial value by the compiler.
The following piece of code is trying to get the address of variable i into pointer variable p but it
won't succeed because i is declared register; therefore following piece of code won't compile
and exit with error "error: address of register variable requested".
#include <stdio.h>
int main()
{
register int i = 10;
int *p = &i; //error: address of register variable requested
void staticDemo()
{
static int i;
{
static int i = 1;
printf("%d ", i);
i++;
}
printf("%d\n", i);
i++;
}
int main()
{
staticDemo();
staticDemo();
}
OUTPUT
KTUQBANK.COM
======
1 0
2 1
• When static specifier is applied to a global variable or a function then compiler makes
that variable or function known only to the file in which it is defined. A static global variable
has internal linkage that means even though the variable is global; routines in other files
have no knowledge of it and cannot access and alter its contents directly. The following C
program defines one static global variable gInt and a static function staticDemo(), for
the variable and function are defined static they cannot be used outside the file (translation
unit) staticdemo.c..
/* staticdemo.c */
#include <stdio.h>
static int gInt = 1;
static void staticDemo()
{
static int i;
printf("%d ", i);
i++;
printf("%d\n", gInt);
gInt++;
}
int main()
{
staticDemo();
staticDemo();
}
OUTPUT
======
0 1
1 2
Static variables have default initial value zero and initialized only once in their lifetime.
extern int x;
KTUQBANK.COM
int main()
{
printf("x: %d\n", x);
}
int x = 10;
Also, if you change the statement extern int x; to extern int x = 50; you will again
get an error "Redefinition of 'x'" because with extern specifier the variable cannot be initialized, if
it is defined elsewhere. If not then extern declaration becomes a definition.
Note that extern can also be applied to a function declaration, but doing so is redundant because
all function declarations are implicitly extern.
Practice Exercises
1. How internal and external linkage are different?
2. How do you make sure if a variable defined with register specifier got stored in CPU
register?
3. Can static global variables be used outside the file in which they have been defined?
4. How declaration of a function is different from its definition?
5. What if you try to assign a value to an extern variable which has already been defined?
References
1. The Complete Reference C
2. The C Programming Language by Brian W Kernighan and Dennis M Ritchie
Bit-wise operations.
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as
follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
KTUQBANK.COM
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −
Operator Description Example
Binary AND Operator copies a bit to the result if it exists
& (A & B) = 12, i.e., 0000 1100
in both operands.
Binary OR Operator copies a bit if it exists in either
| (A | B) = 61, i.e., 0011 1101
operand.
Binary XOR Operator copies the bit if it is set in one
^ (A ^ B) = 49, i.e., 0011 0001
operand but not both.
Binary Ones Complement Operator is unary and has the (~A ) = -61, i.e,. 1100 0011 in
~
effect of 'flipping' bits. 2's complement form.
Binary Left Shift Operator. The left operands value is
<< moved left by the number of bits specified by the right A << 2 = 240 i.e., 1111 0000
operand.
Binary Right Shift Operator. The left operands value is
>> moved right by the number of bits specified by the right
operand.