Академический Документы
Профессиональный Документы
Культура Документы
Day 4
ER/CORP/CRS/LA06/003 1
Session Plan
• Searching & Sorting
– Sorting
• Selection Sort
• Insertion Sort
• Bubble Sort
– Searching
• Linear Search
• Binary Search
ER/CORP/CRS/LA06/003
Copyright © 2004, 2
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 2
Sorting Techniques
•Bubble Sort
•Sorts by comparing adjacent elements and swap whenever required
•Selection Sort
•Sorts the array by selecting the first smallest element,putting it in the first position of
the array, The second smallest element is put in the second position of the array and
so on.
•Insertion Sort
•Sorts the array by inserting each element of the array in a existing presorted array of
elements
ER/CORP/CRS/LA06/003
Copyright © 2004, 3
Infosys Technologies Ltd Version no: 2.0
The sorting refers to the operation of arranging data in some given order, such as increasing
or decreasing (with numerical data) or alphabetically (with character data). There are a
number of sorting methods –Bubble sort, Selection sort, Insertion sort, Heap sort, Quick sort
etc.. The particular method one chooses depends on the properties of the data and the
operations one may perform on the data. However, we will briefly discuss only on the first
three sorting methods implemented for array sorting.
ER/CORP/CRS/LA06/003 3
Bubble Sort
Bubble the smallest element up in the list.
10 23 12 5 23 12 10 5
23 10 12 5 23 12 10 5
23 12 10 5 23 12 10 5
23 12 10 5 23 12 10 5
ER/CORP/CRS/LA06/003
Copyright © 2004, 4
Infosys Technologies Ltd Version no: 2.0
The sorting method followed in Bubble Sort is: Keep passing through the array, exchanging
adjacent elements that are out of order, continuing until the array is sorted. In other word,
“Bubble up” the smallest element to the last location of the array. Implementation of the
Bubble Sort is easier than the Insertion or Selection sort. But bubble sort is generally slower
than the other two methods. Its is slower because it need to scans through the entire array
and swap adjacent elements whenever required. Even the array is sorted number of passes
required is one.
ER/CORP/CRS/LA06/003 4
Bubble Sort Program
#include <stdio.h>
int iRead_Array_Of_Numbers(int []);
int iBubble_Sort(int [], int);
int iBubble(int [], int)
int main()
{
int iNumberOfElements,aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(aiArrNumbers);
iBubble_Sort(iArrNumbers, iNumberOfElements) ;
printf(”The Sorted elements are : ");
for(iIndex = 0; iIndex < iNumberOfElements; iIndex++)
printf("%d",aiArrNumbers[iIndex]);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 5
Infosys Technologies Ltd Version no: 2.0
The efficiency of the sort methods is calculated as number of moves required to sort the
array in the average case and considering only the highest order terms in the result. The
number of moves required for sorting an array using the Bubble Sort is of the order of n2.
ER/CORP/CRS/LA06/003 5
Bubble Sort Program- (Contd..)
ER/CORP/CRS/LA06/003
Copyright © 2004, 6
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 6
Bubble Sort Program-(Contd..)
int iBubble(int aiArr[], int iLast)
{
int iIndex, iSwap;
iSwap = 0;
for(iIndex = 0; iIndex < iLast; iIndex++)
if ( aiArr[iIndex] > aiArr[iIndex + 1] )
{
swap(aiArr, iIndex, iIndex + 1);
iSwap = iSwap +1;
}
return(iSwap);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 7
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 7
Selection Sort
ER/CORP/CRS/LA06/003
Copyright © 2004, 8
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 8
Selection Sort
• Algorithm :
• Find the position p, and the value a[p], of the smallest element in the unsorted
array;
• Swap the element at a[p] with the element at the first position of the unsorted
part of the array.
ER/CORP/CRS/LA06/003
Copyright © 2004, 9
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 9
Selection Sort
9 4 1 7 8 10
1 4 9 7 8 10
ER/CORP/CRS/LA06/003
Copyright © 2004, 10
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 10
Selection Sort
1 4 7 9 8 10
1 4 7 8 9 10
1 4 7 8 9 10
ER/CORP/CRS/LA06/003
Copyright © 2004, 11
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 11
Selection Sort
#include <stdio.h>
int iRead_Array_Of_Numbers(int [ ]);
void vSelection_Sort(int [ ], int);
int iMinimum_In_An_Array(int [ ], int , int);
int iSwap_Elements(int [ ], int , int);
void main( )
{ int iNumberOfElements, aiArrNumbers[10],iIndex;
iNumberOfElements = iRead_Array_Of_Numbers(aiArrNumbers);
iSelection_Sort(aiArrNumbers, iNumberOfElements) ;
printf(”The Sorted elements are : ");
for(iIndex = 0; iIndex < iNumberOfElements; iIndex++)
printf("%d", iArrNumbers[iIndex]);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 12
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 12
Selection Sort
/* Function to sort elements of an array using Selection Sort */
ER/CORP/CRS/LA06/003
Copyright © 2004, 13
Infosys Technologies Ltd Version no: 2.0
A disadvantage of selection sort is that the user of this method might be surprised to find
that it takes about as long to sort an already ordered array as it does for an unordered array!
The number of moves required for sorting an array using the Selection Sort is of the order of
n2.
ER/CORP/CRS/LA06/003 13
Insertion Sort
5 12 18 20
ER/CORP/CRS/LA06/003
Copyright © 2004, 14
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 14
Insertion Sort
Insert the next element into the correct position of the ordered part and, in the
process, extend the ordered section by one element.
Algorithm :
ER/CORP/CRS/LA06/003
Copyright © 2004, 15
Infosys Technologies Ltd Version no: 2.0
Insertion sort works by considering the elements one at a time and inserting the element in
its proper place among those already considered. In other word, the (i+1) th element K[i] is
inserted into its rightful place among K[0], K[1], …, K[i - 1 ], which are previously placed in a
sorted order.
ER/CORP/CRS/LA06/003 15
Insertion Sort Program
#include <stdio.h>
int iRead_Array_Of_Numbers(int []);
int iInsertion_Sort(int [ ], int);
int main( )
{
int iNumberOfElements, aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(aiArrNumbers);
iInsertion_Sort(aiArrNumbers, iNumberOfElements) ;
printf(”The Sorted elements are : ");
for(iIndex = 0; iIndex < iNumberOfElements; iIndex++)
printf("%d", aiArrNumbers[iIndex]);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 16
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 16
Insertion Sort Program
/* Function to sort elements of an array using Insertion Sort */
return(1);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 17
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 17
Which Sorting algo. to use
ER/CORP/CRS/LA06/003
Copyright © 2004, 18
Infosys Technologies Ltd Version no: 2.0
While deciding upon which sorting algorithm to be used there are several things that need to
be considered. Number of comparisons and swaps have a direct impact on the performance
of the code
Bubble sort is the simplest to use and implement but here the #of comparisons and swaps
are more which results in poor performance is the array size is large.
The bubble sort algorithm has a provision to stop once array is sorted.The selection sort, on
the other hand, always needs to go through the same amount of work regardless of the data
The insertion sort is a little better and whilst it cannot detect that it has finished sorting, the
logic of the algorithm means that it comes to a rapid conclusion when dealing with sorted
data.
ER/CORP/CRS/LA06/003 18
Searching
• Heavily used in production programming
• Efficiency is a must
• Lot of techniques available that work on sorted or unsorted arrays. Some of the
techniques are
– Linear Search
– Binary Search
ER/CORP/CRS/LA06/003
Copyright © 2004, 19
Infosys Technologies Ltd Version no: 2.0
Values stored in arrays often need to be queried. Searching techniques play a important
role here
ER/CORP/CRS/LA06/003 19
Linear Search
12 5 23 35
Search value - 5
5 is compared with 10 and then 5 since the match is found no further
comparisons carried out
Search value - 10
10 is compared with 12,5,23,35. But no match is found. However the end of
array has reached without a match so no further comparisons
ER/CORP/CRS/LA06/003
Copyright © 2004, 20
Infosys Technologies Ltd Version no: 2.0
Consider a array of 4 values. In Linear Search, as the number of elements increases, the
time taken to perform the search increases linearly. The linear search requires n
comparisons in the worst case (i.e., when the elements of the array are in the reverse order
of sorting).
ER/CORP/CRS/LA06/003 20
Linear Search
# include <stdio.h>
int iRead_Array_Of_Numbers(int []);
int iLinear_Search(int [ ], int, intt);
int main( )
{
int iPos, iNumberOfElements, iElementToBeSearched, aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(iArrNumbers);
printf (“Enter the element to be searched for : “);
scanf(“%d”, &iElementToBeSearched);
iPos = iLinear_search (aiArrNumbers, iNumberOfElements, iElementToBeSearched) ;
if (iPosOfElement >= 0) { printf("Element is present at %d", iPos); }
else { printf("Element is not present ");}
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 21
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 21
Linear Search
/* Function to search for an element in an array using Linear Search */
int iLinear_search(int aiArr[], int iNoElements, int iNumberToBeSearched)
{
int iFound, iIndex, iFound = 0;
for(iIndex = 0; iIndex < n; iIndex ++ )
if (aiArr[iIndex] == iNumberToBeSearched)
{
iFound =1;
break;
}
if (iFound == 0)
return -1;
else
return iIndex;
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 22
Infosys Technologies Ltd Version no: 2.0
The array is aiArr[] is passed using pass by reference mechanism to the function
ER/CORP/CRS/LA06/003 22
Binary Search
#include <stdio.h>
int iRead_Array_Of_Numbers(int aiArr[ ]);
int iBinary_Search(int aiArr[ ], int iNoElements, int iSearchElement);
int main()
{
int iPosOfElement, iNumberOfElements,iElementToBeSearched,aiArrNumbers[10];
iNumberOfElements=iRead_Array_Of_Numbers(iArrNumbers);
printf (“Enter the element to be searched for : “);
scanf(“%d”, &iElementToBeSearched);
iPosOfElement = iBinary_Search(iArrNumbers,
iNumberOfElements,iElementToBeSearched) ;
if (iPosOfElement >= 0)
printf("Element is present at %d", iPosOfElement);
else
printf("Element is not present ");
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 23
Infosys Technologies Ltd Version no: 2.0
Binary search works by comparing your search element with the center element of the array. Depending on whether the search element
is greater or less than the middle element we now consider second half or the first half of the array and repeat the procedure
The Binary search algorithm is given below.
Arr is an ordered Array of N elements. skey is the key element to be searched for. Low, Middle and High denote the lower, middle and
upper limits of the search interval, respectively.
Algorithm
Start
Step 1 : Low = 1
Step 2 : High = N -1
Step 3 : Repeat Step 4 to Step 5 While Low <= High
Step 4 : Middle = (Low + High) / 2
Step 5 : If ( Arr[Middle] = skey) Then
WRITE “successful search”
Stop
Else If ( skey < Arr[Middle] ) Then High = Middle - 1
Else Low = Middle + 1
End-If
End-If
Step 6 : WRITE “unsuccessful search”
End
Since the searching algorithm works by continuously dividing your array into two parts, in the worst case binary search will require log2
N comparisons to search an element in an array of size N.
ER/CORP/CRS/LA06/003 23
Binary Search
/* Function to search for an element in an array using binary search */
int iBinary_Search(int aiArr[], int iNoElements,
int iNumberToBeSearched)
{
int iLowPos, iHighPos, iMidPos,iLowPos = 0;
iHighPos = iNoElements -1;
while (iHighPos >= iLowPos) {
iMidPos = (iLowPos + iHighPos)/2;
if (iArr[iMidPos] == iNumberToBeSearched)
return iMidPos;
else
if (iArr[iMidPos] < iNumberToBeSearched)
iLowPos = iMidPos + 1;
else
iHighPos = iMidPos -1;
}
return -1;
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 24
Infosys Technologies Ltd Version no: 2.0
In the array implementation of Linear Search, we can improve significantly the search time if
the array is already ordered by using a search method known as Binary Search.
ER/CORP/CRS/LA06/003 24
/*Read the data into the array*/
int iRead_Array_Of_Numbers(int aiArr[ ]){
int iNumber;
iNumber =0;
Choice = ‘y’;
while(Choice == ‘Y’ || Choice == ‘y’)
{
printf(“\n Enter the %d element “, iNumber + 1);
fflush(stdin);
scanf(“%d”, &aiArr[iNumber - 1]);
iNumber = iNumber + 1;
printf(“\nDo you want to continue: enter (y/n)”);
fflush(stdin);
scanf(“%c”,&Choice);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 25
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 25
I/O Streams in C
ER/CORP/CRS/LA06/003
Copyright © 2004, 26
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 26
File Handling Functions in C
Basic operations to be carried out on files
1. Opening of file
2. Closing of file
3. Reading file
4. Writing file
5. Traversing the pointer
6. Checking for end of file
7. Get the current position in file
For all the file handling operations the pointer to file is created which is of the
data type :-
FILE pointer – data type defined in stdio.h
Eg. FILE *fp;
ER/CORP/CRS/LA06/003
Copyright © 2004, 27
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 27
Opening File
fopen() - opens a file in the mode specified
Prototype declaration – FILE *fopen(“filename” “mode”);
ER/CORP/CRS/LA06/003
Copyright © 2004, 28
Infosys Technologies Ltd Version no: 2.0
Your program must open a file before it can access it. This is done using the fopen function,
which returns the required file pointer. If the file cannot be opened for any reason then the
value NULL will be returned.
You will usually use fopen as follows
if ((output_file = fopen("output_file", "w")) == NULL) fprintf(stderr, "Cannot open %s\n",
"output_file");fopen takes two arguments, both are strings, the first is the name of the file to
be opened, the second is an access character, which is usually one from the above table
ER/CORP/CRS/LA06/003 28
Examples of fopen calls
ER/CORP/CRS/LA06/003
Copyright © 2004, 29
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 29
Closing File
fclose() - opens a file in the mode specified
Prototype declaration – int fclose(FILE *);
ER/CORP/CRS/LA06/003
Copyright © 2004, 30
Infosys Technologies Ltd Version no: 2.0
The fclose command can be used to disconnect a file pointer from a file. This is usually done
so that the pointer can be used to access a different file. Systems have a limit on the number
of files which can be open simultaneously, so it is a good idea to close a file when you have
finished using it.
This would be done using a statement like
fclose(output_file); If files are still open when a program exits, the system will close them for
you. However it is usually better to close the files properly.
The function fclose is used to close the file i.e. indicate that we are finished processing this
file.
We could reuse the file pointer fp by opening another file. Always remember to close a file
before reopening the file in any other mode.
ER/CORP/CRS/LA06/003 30
Formatted Input/Output
The functions fscanf and fprintf provide the equivalent for any open file.
Their prototypes:
int fscanf(FILE *fp, char *format, arg1, arg2, ...);
int fprintf(FILE *fp, char *format, arg1, arg2, ...);
For Exmaple
ER/CORP/CRS/LA06/003
Copyright © 2004, 31
Infosys Technologies Ltd Version no: 2.0
The fscanf and fprintf function work in a similar manner as scanf and printf.
Arguments to fscanf are in addition to the format stirng and the variable list , pointer to the
file from which read operation needs to be done.
Arguments to printf are in addition to the format stirng and the variable list , pointer to the file
on which write operation needs to be done.
ER/CORP/CRS/LA06/003 31
Character / String Input
char *fgets (char *s, int n, FILE *fp);
char *gets(char *s);
• fgets reads characters into the array s, from file * fp until a newline or n-1
characters have been read
– It returns NULL if an error or EOF occurs.
• fgets retains any newline characters
– gets does not
• make sure the character array s is large enough to hold all the data being
read!
• fgets is quite useful when you don't know how many lines a file contains
• keep reading line-by-line it returns NULL
• then use sscanf(char * s, char *format, arg1, arg2, ...)
to break a string s into parts
sscanf(line, "%s %d", name, &age);
• breaks line into a string variable name and integer variable age
ER/CORP/CRS/LA06/003
Copyright © 2004, 32
Infosys Technologies Ltd Version no: 2.0
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).
Thus the statement “ c = getc(fp); “ reads the next character from the file referenced by fp and
the statement “putc(c,fp); “ writes the character c into file referenced by fp
ER/CORP/CRS/LA06/003 32
File input example
char line[50], name[30];
int age;
FILE * fp;
fp = fopen("Names.txt", "r");
if (fp != NULL) {
while (fgets(line, 49, fp) != NULL) {
sscanf(line, "%s %d", name, &age);
printf("Name is %s, age is %d\n", name, age);
}
printf("End of file");
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 33
Infosys Technologies Ltd Version no: 2.0
Names.txt is a file already created using a text editor. Each line in the file contains a name
followed by an integer age.
ER/CORP/CRS/LA06/003 33
Simple Example Code
#include <stdio.h>
main () {
FILE *fp1,*fp2,*fp3;
char filename[32];
char result[30]="";
int letter;
fp1 = fopen("mydata.txt","r");
fp2 = fopen("results.txt","w");
printf("Name of output file: ");
scanf("%s",filename);
fp3= fopen(filename,"a");
fgets(result, 12, fp1);
printf("The first file contains: %s", result);
fputs(result,fp2);
letter='a';
fputc(letter,fp3);
fclose(fp1);fclose(fp2);fclose(fp3);
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 34
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 34
Some More Examples
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> int m ain()
int m ain() {
{ F ILE *in, *out; int key;
int num ; char buffer[20]; if ((in = fopen("junk.txt", "r"))
printf("E nter a num ber: "); /* == N U LL)
U se the fgets function to {
validate input */ puts("U nable to open the
fgets(buffer, 20, stdin); file"); return 0;
num = atoi(buffer); }
printf("T he num ber you out = fopen("copy.txt", "w");
entered was % d\n", num ); while (!feof(in))
return 0; {
} key = fgetc(in);
if (!feof(in)) fputc(key, out);
}
fclose(in);
fclose(out);
return 0;
}
ER/CORP/CRS/LA06/003
Copyright © 2004, 35
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 35
File Functions : Used in Project
• int fiOpenFile(int iFile)
ER/CORP/CRS/LA06/003
Copyright © 2004, 36
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 36
File open: fiOpenFile
ER/CORP/CRS/LA06/003
Copyright © 2004, 37
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 37
Read file : fiReadFile
• Prototype : int fiReadFile ( char acLine[ ],
int iFile, int ipos)
– Parameters :
– acLine - A string: The string that is read from the file.
– iFile - integer :
» DEP_FILE to read dept.txt
» EMP_FILE to read emp.txt
– ipos - integer :
» BEGIN to read from the beginning.
» CURRENT to read from the current position.
– Return value: The function returns 1 on success and 0 on
failure.
– Remarks :
– The function reads a line into acLine from the file that
specified by iFile argument.
– If ipos is BEGIN it reads from the first line.
– If ipos is CURRENT it reads the line from current-position.
ER/CORP/CRS/LA06/003
Copyright © 2004, 38
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 38
Write file : fvWriteFile
ER/CORP/CRS/LA06/003
Copyright © 2004, 39
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 39
Update file : fiUpdateFile
• Prototype: int fiUpdateFile (char acLine[ ],
int iFile)
– Parameters :
• acLine - A string:
– The string that is written into the file.
• iFile - integer :
– DEP_FILE to open dept.txttxt,
– EMP_FILE to open emp.txt.
– Return value: The function returns 1 on success and 0 on
failure.
– Remarks :
• The function updates a line in the file as specified by iFile
argument. The string as in argument sLine will replace the line.
It will be the line, which is last read from the file by fiReadFile
function.
ER/CORP/CRS/LA06/003
Copyright © 2004, 40
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 40
Close file: fiCloseFile
• Parameters :
• iFile - integer :
– DEP_FILE to open dept.txt,
– EMP_FILE to open emp.txt.
– Return value: The function returns 1 on success and 0 on failure.
– Remarks: The function closes the file.
ER/CORP/CRS/LA06/003
Copyright © 2004, 41
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 41
Summary
• Various sorting and searching methods
ER/CORP/CRS/LA06/003
Copyright © 2004, 42
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 42
Thank You!
ER/CORP/CRS/LA06/003
Copyright © 2004, 43
Infosys Technologies Ltd Version no: 2.0
ER/CORP/CRS/LA06/003 43