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

PPS Unit-V Full Notes

The document discusses file handling in C programming. It covers why files are needed, different file types (text and binary), file operations like opening, reading, writing and closing files. It also discusses file streams, declaring and opening files, different file opening modes, and provides an example of creating a sequential access file to store account details.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
122 views

PPS Unit-V Full Notes

The document discusses file handling in C programming. It covers why files are needed, different file types (text and binary), file operations like opening, reading, writing and closing files. It also discusses file streams, declaring and opening files, different file opening modes, and provides an example of creating a sequential access file to store account details.

Uploaded by

sirisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Programming for Problem Solving using C

Unit-V
UNIT – V
File Handling: I/O streams, File operations, file modes, Sequential, Random
accessing of files, Command line arguments
Searching and Sorting Techniques: Searching-Linear search and Binary
search, Sorting- Bubble sort and Selection sort
FILE

Why files are needed?

 When a program is terminated, the entire data is lost. Storing in a file will
preserve your data even if the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter
them all.However, if you have a file containing all the data, you can easily
access the contents of the file using few commands in C.
 You can easily move your data from one computer to another without any
changes.

File I/O:-

Sometimes it is necessary to store the data in a manner that can be later retrieved and
displayedeither in a part or in whole. This medium is usually a “file” on the disk.

File I/O can be handled by using different functions.

a) Formatted functions:- The file input function fscanf( ) and the file output function
fprintf( )are called formatted file I/O functions.

b)Unformatted functions:- The input functions like getc( ), getw( ), and fread( ) are
called unformatted file input functions and putc( ), putw( ), and fwrite( ) functions are
unformatted file output functions. Each and every function is having its own syntax
and meaning.

File streams:- Stream is either reading or writing of data. The streams are designed to
allow the user to access the files efficiently. A stream is a file or physical device like
key board, printer,monitor, etc., The FILE object uses these devices. When a C
program is started, the operating system is responsible for opening three streams:
standard input stream (stdin), standard output stream (stdout), standard
error(stderr).Normally the stdin is connected to the keyboard, the stdout and stderr
are connected to the monitor.

Files

File is a collection of bytes that is stored on secondary storage devices like Hard disk.

OR
Programming for Problem Solving using C
Unit-V
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.

Note: All files related function are available in stdio.h header file.

Types of Files

When dealing with files, there are two types of files you should know about:

1. Text files

2. Binary files

1. Text files

Text files are the normal .txt files that you can easily create using Notepad or any
simple text editors.

When you open those files, you'll see all the contents within the file as plain text. You
can easily edit or delete the contents.

They take minimum effort to maintain, are easily readable, and provide least security
and takes bigger storage space.

2. Binary files

Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better
security than text files.

File Operations

In C, you can perform four major operations on the file, either text or binary:

 Naming a file/Creation of new file


 Opening an existing file
 Reading data from file
 Writing data into file
 Closing a file

Steps for processing a file

 Declare a file pointer


 open a file using fopen() function
 Process the file using suitable file functions.
 close the file using fclose() function.
Programming for Problem Solving using C
Unit-V
Declaration of a file

When working with files, you need to declare a pointer of type file. This declaration is
needed

for communication between the file and program.

Syntax

FILE *fp;

Opening a file - for creation and edit

The fopen() function is used to create a new file or to open an existing file.

General Syntax :

fp = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Closing a File

The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be closed.

DEFINING AND OPENING A FILE:

Steps involved in file usage are

1) Declare file variable, data structure

2) Open the file with purpose (Filename,Purpose-read,write,update)

3) Process the file with purpose

4) Close the file

File name is a group of characters that make up a valid file name for the
operating system. It may contain two parts, a primary name and an optional period
with the extension.

Examples: abc.dat
Programming for Problem Solving using C
Unit-V
Xyz.txt

Prog.c

Stu.cpp

1) Data structure of a file is defined as FILE in the library of standard I/O function
definitions. Therefore, all files should be declared as type FILE before they are used.
FILE is a defined data type.

When we open a file, we must specify what we want to do with the file. For
example we may write data to the file or read the data from already existing file.

Following is the general format for declaring and opening a file

FILE *fptr;(fptr is pointer variable)

The above statement declares the variable fptr as a “pointer to the data type FILE”.

2) To open the file use the command fopen() as follows

Fptr=fopen(―filename‖,‖mode‖);

fopen() opens the named file name and assigns an identifier to the FILE type pointer
fptr. This pointer, which contains all the information about the file, is subsequently
used as a communication link between the system and the program.

This statement also specifies the purpose of opening this file. The mode does
this job.

Note that both the filename and mode are specified as strings. They should be
enclosed in double quotation marks. Consider the following statements:

Ex.

FILE *p1,*p2;

P1=fopen(“data”,”r”);--This statement say as the data file is opened in read mode.

P2=fopen(“result”,”w”); --This statement say as the result file is opened in write


mode.

3) Using the C statements process the data for which purpose the file is opened.

Like computations and storing the information using I/O statements


Programming for Problem Solving using C
Unit-V
4) CLOSING A FILE:

A file must be closed as soon as all operations on it have been completed. This
ensures that all outstanding information associated with the file is flushed out from
the buffers and all links to the file are broken. It also prevents any accidental misuse
of the file. In case, there is a limit to the number of files that can be kept open
simultaneously, closing of unwanted files might help open the required files. Another
instance where we have to close a file is when we want to reopen the same file in a
different mode. The I/O library supports a function to do this for us . It takes the
following form

fclose(file_ptr);

This would close the file associated with the FILE pointer file-pointer.

Ex: fclose(p1);

As a matter of fact all file are closed automatically whenever a program terminates.
However, closing a file as soon as you are done with it is a good programming habit.

CREATING A SEQUENTIAL-ACCESS FILE

C imposes no structure for a file. Thus, notaions like a record of a file do not
exist as part of the C language. Therefore, the programmer must provide any file
structure to meet the requirement of each particular application.

The following program creates a simple sequential –access file that might be
used in an accounts receivable system to help keep track of the amounts owed by a
company’s credit clients.

/*Program to create sequential access file */

#include<stdio.h>

#include<conio.h>

void main()

int account;

char name[30];

double balance;
Programming for Problem Solving using C
Unit-V
FILE *cfptr;/* cfptr=clients.dat file pointer*/

if((cfptr=fopen("clients.dat","w"))==NULL)

printf("File could not be searche");

else

{ printf("Enter the account,name and balance((ctrl+z) to stop input)\n");

scanf("%d%s%lf",&account,name,&balance);

while(!feof(stdin))

fprintf(cfptr,"%d%s%.2f",account,name,balance);

scanf("%d%s%lf",&account,name,&balance);

fclose(cfptr);

OUTPUT: Enter the account, name and balance ( (ctrl+z) to stop input)

100 Jones 24.98

200 Doe 345.67

300 White 0.00

400 Stone -42.16

500 Rich 224.62

File Opening Modes

Mode Description
r opens a text file in read mode
w opens a text file in write mode
Programming for Problem Solving using C
Unit-V
a opens a text file in append mode
r+ opens a text file in read and write
mode
w+ opens a text file in read and write
mode
a+ opens a text file in read and write
mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both
are used to write in a file. In both the modes, new file is created if it doesn't exists
already.

The only difference they have is, when you open a file in the write mode, the file is
reset, resulting in deletion of any data already present in the file. While in append
mode this will nothappen. Append mode is used to append or add data to the existing
data of file(if any). Hence,when you open a file in Append(a) mode, the cursor is
positioned at the end of the present data in the file.

File accessing method are two types 1) Sequential 2) Random access files.

1. Sequential Access — The data are placed in the file in a sequence like
beads on a string. Data are processed in sequence, one after another. To
reach a particular item of data, all the data that proceeds it first must be
read.

2. Random Access — The data are placed into the file by going directly to the
location in the file assigned to each data item. Data are processed in any
order. A particular item of data can be reached by going directly to it,
without looking at any other data.

Formatted File I/O Functions

Syntax of fprintf is
Programming for Problem Solving using C
Unit-V
fprintf (fp, “control string”, list);

Example: fprintf(fp1, “%s %d”, name, age);

Syntax of fscanf is,

fscanf(fp, “control string”, list);

Example: fscanf(fp, “%s %d”, name, & age);

Note:

 fscanf is used to read list of items from a file


 fprintf is used to write a list of items to a file.

Note:

EOF – End of file (when EOF encountered the reading / writing should be terminated)

Example:

#include <stdio.h>

main(){

FILE *fp;

fp = fopen("file.txt", "w");//opening file

fprintf(fp, "Hello file by fprintf...\n");//writing data into file

fclose(fp);//closing file

Example 1: Write to a text file using fprintf()

#include <stdio.h>

int main()

int num;

FILE *fptr;

fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
Programming for Problem Solving using C
Unit-V
{

printf("Error!");

exit(1);

printf("Enter num: ");

scanf("%d",&num);

fprintf(fptr,"%d",num);

fclose(fptr);

return 0;

Example 2: Read from a text file using fscanf()

#include <stdio.h>

int main()

int num;

FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){

printf("Error! opening file");

// Program exits if the file pointer returns NULL.

exit(1);

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);

fclose(fptr);

return 0;

}
Programming for Problem Solving using C
Unit-V
Input/Output Operation on files

To perform Input/Output Operation on files we need below functions.

S.No Function Operation Syntax

1. getc() Read a character getc( fp)


from a file
2. putc() Write a character in putc(c, fp)
file
3. fprintf() To write set of data fprintf(fp, "control
in file string", list)

4. fscanf() To read set of data fscanf(fp, "control


from file. string", list)

5. getw() To read an integer getw(fp)


from a file
6. putw() To write an integer putw(integer, fp)
in file

Unformatted File I/O Functions

fputc() function

The fputc() function is used to write a single character into file.

 putc ( ):-Putting a character in to the file. It works with only character data
type. One character at a time can write into a file.

Ex: char ch =‟a‟;

putc (ch, fp);

Example:

#include <stdio.h>

main(){

FILE *fp;

fp = fopen("file1.txt", "w");//opening file

fputc('a',fp);//writing single character into file

fclose(fp);//closing file
Programming for Problem Solving using C
Unit-V
}

file1.txt

fgetc() function

The fgetc() function returns/read a single character from the file. It gets a character
from the

stream. It returns EOF at the end of file.

 getc ( ): getting a character from the file, or reading the file information
character by character at a time, upto the end of the file by using this function.

Ex: char ch;

ch = getc (fp);

Example:

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

char c;

clrscr();

fp=fopen("myfile.txt","r");

while((c=fgetc(fp))!=EOF){

printf("%c",c);

fclose(fp);

getch();

Output:

myfile.txt
Programming for Problem Solving using C
Unit-V
this is simple text message

 fputs()

The fputs() function writes a line of characters into file

Example:

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

clrscr();

fp=fopen("myfile2.txt","w");

fputs("hello c programming",fp);

fclose(fp);

getch();

Output:

myfile2.txt

hello c programming

 fgets()

The fgets() function reads a line of characters from file.

Example:

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

char text[300];
Programming for Problem Solving using C
Unit-V
clrscr();

fp=fopen("myfile2.txt","r");

printf("%s",fgets(text,200,fp));

fclose(fp);

getch();

Output:

hello c programming

 The getw and putw functions:

These are integer oriented functions. These are similar to above functions and are
used to readand write integer values. These are useful when we deal with only integer
data. The general format is

putw ( ): putting or writing of an integer value to a file.

putw (integer , fp);

Ex: int x = 5;

putw(x,fp);

getw ( ): getting or reading integer value from a file.

Ex: int x;

x = getw (fp);

Random accessing of files

1.fseek()

The fseek() function is used to set the file pointer to the specified offset. It is used to
write datainto file at desired location.

syntax: fseek(FILE * stream, long int offset, int whence)

The first parameter stream is the pointer to the file. The second parameter is the
position of the record to be found, and the third parameter specifies the location where
the offset starts.Different Whence in fseek
Programming for Problem Solving using C
Unit-V
Whence Meaning

SEKK_SET Starts the offset from the beginning of the file.

SEKK_END Starts the offset from the end of the file.

SEKK_CUR Starts the offset from the current location of the cursor in the file.

or

fseek(file pointer, offset, position);

 file pointer is a pointer to the concerned file.


 Offset is a number or variable of type long, it specifies the number of positions
(bytes) to be moved from the location specified. If offset is positive number, then
moving forward or negative meaning move backwards.
 Position is a n integer number and it specifies from which position the file
pointer to be moved. Position can take one of the following three values.

0 beginning of file

1 current position

2 end of file

Eg: fseek (fp, 0L,0); - go to the beginning of the file. (Similar to rewind).

fseek (fp, 0L,1); - Stay at current position (Rarely used)

fseek (fp, 0L,2); -go to the end of the file, past the last character of the file.

Example:

#include <stdio.h>

void main(){

FILE *fp;

fp = fopen("myfile.txt","w+");

fputs("This is javatpoint", fp);

fseek( fp, 7, SEEK_SET );

fputs("sonoo jaiswal", fp);

fclose(fp);

}
Programming for Problem Solving using C
Unit-V
myfile.txt

This is sonoo jaiswal

2.rewind()

This function places the file pointer to the beginning of the file, irrespective of where it
is present right now. It takes file pointer as an argument.

Syntax:

rewind( fp);

Example:

File: file.txt

this is a simple text

Example:

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

char c;

clrscr();

fp=fopen("file.txt","r");

while((c=fgetc(fp))!=EOF){

printf("%c",c);

rewind(fp);//moves the file pointer at beginning of the file

while((c=fgetc(fp))!=EOF){

printf("%c",c);

fclose(fp);
Programming for Problem Solving using C
Unit-V
getch();

} Output:

this is a simple text this is a simple text

As you can see, rewind() function moves the file pointer at beginning of the file that is
why "this is simple text" is printed 2 times. If you don't call rewind() function, "this is
simple text" will be printed only once.

3.ftell()

The ftell() function returns the current file position of the specified stream. We can use
ftell()

function to get the total size of a file after moving file pointer at the end of file. We can
use

SEEK_END constant to move the file pointer at the end of file.

syntax:

n = ftell(fp);

n would give the relative offset(in bytes).

Example:

#include <stdio.h>

#include <conio.h>

void main (){

FILE *fp;

int length;

clrscr();

fp = fopen("file.txt", "r");

fseek(fp, 0, SEEK_END);

length = ftell(fp);

fclose(fp);

printf("Size of file: %d bytes", length);

getch();
Programming for Problem Solving using C
Unit-V
}

Output:

Size of file: 21 bytes

Command Line Argument in C

So far we have seen how to input values in C code during compile-time and runtime.
To do that, we declared variables in the main() and then worked on them but there is a
way to input values without declaring it in the main().

C offers us a feature called "command line argument" using which we can enter
values from the command line at the time of execution. Command line argument is a
parameter supplied to the program when it is invoked or run.

Use of Command Line arguments in C

 They are used when we need to control our program from outside instead of
hard-coding it.
 They make installation of programs easier.

Command line argument is an important concept in C programming. Command line


arguments are passed to the main() method.

Syntax:

int main(int argc, char *argv[])

Here, argc counts the number of arguments on the command line and argv[ ] is
a pointer array which holds pointers of type char which points to the arguments
passed to the program.

Let's see a simple code example to check whether any command line arguments is
provided to the code or not..

#include<stdio.h>

int main(int argc, char *argv[])

if(argc < 2)

printf("No argument supplied. The only argument here is %s", argv[0]);


Programming for Problem Solving using C
Unit-V
return 0;}

Compile the above code using: gcc filename.c -o filename

Then run it using: ./filename

From the above example, we can infer that the first command line argument
is the program file name, which is always added by default by the compiler.

Hence, argv[0] = name of our file and argc = 1.

Example for Command Line Argument

If we want to print all the arguments in our program, we can do it as follows.

#include <stdio.h>
#include <conio.h>
int main(int argc, char *argv[])
{
int i;
if( argc >= 2 )
{
printf("The arguments supplied are:\n");
for(i = 1; i < argc; i++)
{
printf("%s\t", argv[i]);
}
}
else
{
printf("argument list is empty.\n");
}
return 0;
}
Compile the above code using command: gcc name_of_file.c, then run it
using: ./a.out Welcome to Studytonight, we have provided command line argument
while running the compiled code.

1 : Welcome
2 : to
3 : Studytonight
Programming for Problem Solving using C
Unit-V
We provided 3 words seperated by space as arguments, while running the code.
So, they will be considered as three separate arguments.

some more examples...

Let's see how inclusion of quotes changes the output of the same program.

Compile the above code again: gcc name_of_file.c

Run it using: ./a.out "welcome to studytonight"

1 : welcome to studytonight
Here, we have provided all the 3 words enclosed in a double quote. So, it is
considered as a single argument. Same thing happens with single quotes.

Compile the same code again: gcc name_of_file.c

Then, run it using: ./a.out 'welcome to studytonight'

1 : welcome to studytonight
Similarly, we can give int and float type arguments but they will be treated
as strings.

Again compile the above code: gcc name_of_file.c

And run it using: ./a.out 1 0 a 5.07

1:1
2:0
3:a
4 : 5.07
Programming for Problem Solving using C
Unit-V

INTRODUCTION TO SEARCHING ALGORITHMS

Searching is an operation or a technique that helps finds the place of a given element
or value in the list. Any search is said to be successful or unsuccessful depending
upon whether the element that is being searched is found or not. Some of the
standard searching technique that is being followed in data structure is listed below:

1. Linear Search

2. Binary Search

LINEAR SEARCH

Linear search is a very basic and simple search algorithm. In Linear search, we search
an element or value in a given array by traversing the array from the starting, till the
desired elementor value is found.

It compares the element to be searched with all the elements present in the array and
when the element is matched successfully, it returns the index of the element in the
array, else it return -1.

Linear Search is applied on unsorted or unordered lists, when there are fewer
elements in a list.

For Example,

Linear Search

33

Linear Search
Linear search is a sequential searching algorithm where we start from one end and check every
element of the list until the desired element is found. It is the simplest searching algorithm.
Programming for Problem Solving using C
Unit-V
How Linear Search Works?
The following steps are followed to search for an element k = 1 in the list below.

Array to be searched for

1. Start from the first element, compare k with each element x . Compare with each element

2. If x == k , return the index

.
Element found
Programming for Problem Solving using C
Unit-V
3. Else, return not found .

Algorithm

Linear Search ( Array A, Value x)

Step 1: Set i to 1

Step 2: if i > n then go to step 7

Step 3: if A[i] = x then go to step 6

Step 4: Set i to i + 1

Step 5: Go to Step 2

Step 6: Print Element x Found at index i and go to step 8

Step 7: Print element not found

Step 8: Exit

Pseudocode

procedure linear_search (list, value)

for each item in the list

if match item == value

return the item‟s location

end if

end for

end procedure

Features of Linear Search Algorithm

1. It is used for unsorted and unordered small list of elements.

2. It has a time complexity of O(n), which means the time is linearly dependent on the
Programming for Problem Solving using C
Unit-V
number of elements, which is not bad, but not that good too.

3. It has a very simple implementation.

BINARY SEARCH

Binary Search is used with sorted array or list. In binary search, we follow the
following

steps:

1. We start by comparing the element to be searched with the element in the middle of

the list/array.

2. If we get a match, we return the index of the middle element.

3. If we do not get a match, we check whether the element to be searched is less or

greater than in value than the middle element.

4. If the element/number to be searched is greater in value than the middle number,

then we pick the elements on the right side of the middle element(as the list/array is

sorted, hence on the right, we will have all the numbers greater than the middle

number), and start again from the step 1.

5. If the element/number to be searched is lesser in value than the middle number,


then we pick the elements on the left side of the middle element, and start again from
the

step 1.

Binary Search is useful when there are large number of elements in an array and they
are sorted. So a necessary condition for Binary search to work is that the list/array
should be sorted.

Features of Binary Search

1. It is great to search through large sorted arrays.

2. It has a time complexity of O(log n) which is a very good time complexity. It has a

simple implementation.
Programming for Problem Solving using C
Unit-V
Binary search is a fast search algorithm with run-time complexity of Ï(log n). This
search algorithm works on the principle of divide and conquers. For this algorithm to
work properly, the data collection should be in the sorted form.

Binary search looksfor a particular item by comparing the middle most item of the
collection.If a match occurs, then the index of item is returned. If the middle item is
greater than the item,then the item is searched in the sub-array to the left of the
middle item. Otherwise, the item issearched for in the sub-array to the right of the
middle item. This process continues on the subarray as well until the size of the sub
array reduces to zero.

How Binary Search Works?

For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example. The following is our sorted
array and let us assume that we need to search the location of value 31 using binary
search.

First, we shall determine half of the array by using this formula -

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.

Now we compare the value stored at location 4, with the value being searched, i.e. 31.
We

find that the value at 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.
Programming for Problem Solving using C
Unit-V

We change our low to mid + 1 and find the new mid value again.

low = mid + 1

A ! sorted array

n ! size of array

x ! value to be searched

Set lowerBound = 1

Set upperBound = n

while x not found

mid = low + (high - low) / 2

Our new mid is 7 now. We compare the value stored at location 7 with our target value
31.

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.

Hence, we calculate the mid again. This time it is 5.


Programming for Problem Solving using C
Unit-V

We compare the value stored at location 5 with our target value. We find that it is a
match.

We conclude that the target value 31 is stored at location 5.

Binary search halves the searchable items and thus reduces the count of comparisons
to bemade to very less numbers.

Pseudocode

The pseudocode of binary search algorithms should look like this “

Procedure binary_search

A ! sorted array

n ! size of array

x ! value to be searched

Set lowerBound = 1

Set upperBound = n

while x not found

if upperBound < lowerBound

EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

if A[midPoint] < x

set lowerBound = midPoint + 1


Programming for Problem Solving using C
Unit-V
if A[midPoint] > x

set upperBound = midPoint - 1

if A[midPoint] = x

EXIT: x found at location midPoint

end while

end procedure

SORTING
Preliminaries

A sorting algorithm is an algorithm that puts elements of a list in a certain order. The
most used orders are numerical order and lexicographical order. Efficient sorting is
important to optimizing the use of other algorithms that require sorted lists to work
correctly and for producing human - readable input.

Sorting algorithms are often classified by :

* Computational complexity (worst, average and best case) in terms of the size of the
list (N).For typical sorting algorithms good behaviour is O(NlogN) and worst case
behavior is O(N2) and the average case behaviour is O(N).

* Memory Utilization

* Stability - Maintaining relative order of records with equal keys.

* No. of comparisions.

* Methods applied like Insertion, exchange, selection, merging etc. Sorting is a process
of linear ordering of list of objects.

Sorting techniques are categorized into

 Internal Sorting
 External Sorting

Internal Sorting takes place in the main memory of a computer.

if upperBound < lowerBound


Programming for Problem Solving using C
Unit-V
EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

if A[midPoint] < x

set lowerBound = midPoint + 1

eg : - Bubble sort, Insertion sort, Shell sort, Quick sort, Heap sort, etc.

External Sorting, takes place in the secondary memory of a computer, Since the
number of objects to be sorted is too large to fit in main memory.

eg : - Merge Sort, Multiway Merge, Polyphase merge.

THE BUBBLE SORT

The bubble sort makes multiple passes through a list. It compares adjacent items and
exchanges those that are out of order. Each pass through the list places the next
largest value in its proper place. In essence, each item “bubbles” up to the location
where it belongs.

Fig. 5.1 shows the first pass of a bubble sort. The shaded items are being compared to
see if they are out of order. If there are n items in the list, then there are n - 1n - 1
pairs of items that need to be compared on the first pass. It is important to note that
once the largest value in the list is part of a pair, it will continually be moved along
until the pass is complete.

Working of Bubble Sort


Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the second elements.

2. If the first element is greater than the second element, they are swapped.

3. Now, compare the second and the third elements. Swap them if they are not in order.

The above process goes on until the last element.


Programming for Problem Solving using C
Unit-V

2. Remaining Iteration

The same process goes on for the remaining iterations.


After each iteration, the largest element among the unsorted elements is placed
at the end.

In each iteration, the comparison takes place up to the last unsorted element.
Programming for Problem Solving using C
Unit-V

The array is sorted when all the unsorted elements are placed at their correct positions.

#include<stdio.h>
bubblesort(int a[],int n)
{
int temp,p,c;
for(p=1;p<=n-1;p++)
{
for(c=1;c<=n-p;c++)
{
if(a[c]>a[c+1])
{
temp=a[c];
Programming for Problem Solving using C
Unit-V
a[c]=a[c+1];
a[c+1]=temp;
}
}
}
}

int main()
{
int a[5],n,i;
printf("enter n value");
scanf("%d",&n);
printf("enter %d elements into array",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
bubblesort(a,n);
printf("after sauting elements are");
for(i=1;i<=n;i++)
printf("%d\t",a[i]);
return 1;
}
Output:

Selection Sort Algorithm

Selection Sort algorithm is used to arrange a list of elements in a particular

order (Ascending or Descending). In selection sort, the first element in the list

is selected and it is compared repeatedly with all the remaining elements in the

list. If any element is smaller than the selected element (for Ascending order),
Programming for Problem Solving using C
Unit-V

then both are swapped so that first position is filled with the smallest element

in the sorted order. Next, we select the element at a second position in the list

and it is compared with all the remaining elements in the list. If any element is

smaller than the selected element, then both are swapped. This procedure is
repeated until the entire list is sorted.

Step by Step Process

The selection sort algorithm is performed using the following steps...

 Step 1 - Select the first element of the list (i.e., Element at first position

in the list).

 Step 2: Compare the selected element with all the other elements in the

list.

 Step 3: In every comparision, if any element is found smaller than the

selected element (for Ascending order), then both are swapped.

 Step 4: Repeat the same procedure with element in the next position in
the list till the entire list is sorted.

Following is the sample code for selection sort...


Selection Sort Logic
//Selection sort logic

for(i=0; i<size; i++){


for(j=i+1; j<size; j++){
if(list[i] > list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
Programming for Problem Solving using C
Unit-V
}

Example:

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.

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.
Programming for Problem Solving using C
Unit-V
The same process is applied to the rest of the items in the array.

Following is a pictorial depiction of the entire sorting process −


Programming for Problem Solving using C
Unit-V

Complexity of the Selection Sort Algorithm

To sort an unsorted list with 'n' number of elements, we need to make ((n-

1)+(n-2)+(n-3)+......+1) = (n (n-1))/2 number of comparisions in the worst case.


If the list is already sorted then it requires 'n' number of comparisions.

WorstCase: O(n2)

BestCase: Ω(n2)
Average Case : Θ(n2)
Implementaion of Selection Sort Algorithm using C Programming
Language
#include<stdio.h>
#include<conio.h>

void main(){

int size,i,j,temp,list[100];
clrscr();

printf("Enter the size of the List: ");


scanf("%d",&size);

printf("Enter %d integer values: ",size);


for(i=0; i<size; i++)
scanf("%d",&list[i]);

//Selection sort logic

for(i=0; i<size; i++){


for(j=i+1; j<size; j++){
if(list[i] > list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
Programming for Problem Solving using C
Unit-V
}
}

printf("List after sorting is: ");


for(i=0; i<size; i++)
printf(" %d",list[i]);

getch();
}

Output:

You might also like