UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 1
CS201: Data Structure and Algorithms
Class: BSCS-2k19
Lab 1: Basic concepts in C++
Date: October 12, 2021
Time: 1200 to 1500
Instructor: Marriam Nawaz
marriam.nawaz@uettaxila.edu.pk
Lab Manual 03
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 2
Lab Manual 3
Introduction
This lab is about the Operations on Arrays in C++.
Objectives
The objectives of this session is to understand the various operations on arrays in C++.
Tools/Software Requirement
Dev C++
Goals for today’s lab:
 Understanding array operations and write it’s algorithm.
 Convert algorithm to practical implementation.
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 3
Basic concepts
What is menat by Data Structure?
Organization of information so that machines and humans can better understand it.
What is an algorithm?
Sequence of steps to solve a particluer problem.
Types of Data Strucure
(Liner, non-linear)
Operation you can perform on data
 Insetion
 Deletion
 Traversing
 Searching
 sorting
Linear Data structure
1. Arrays: collection of similar data items.
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 4
Opertion on Arrays
 Insertion Algortithm and code
Algorithm InsertLA (DATA, N, ITEM, LOC)
Desc: This algorithm inserts new element ITEMin linear array DATA with N elements
If LOC=1 it means the element has to insert in beginning
If LOC =N+1 it means the element have to be inserted at the end
If LOC = J it means the elements have to be inserted at Jth Location
Begin
Step 1: [Initialize counter I with index of last element]
I=N
Step 2: While I>=LOC repeat steps 3 and 4
Step 3: [Move the current element one position backwards]
DATA[I+1]=DATA[I]
Step 4: [Decrement counter I]
I=I-1
Step 5:[Insert new element at the Location]
DATA[LOC]=ITEM
Step 6:[ Update total under of array elements]
N=N+1
Exit
Code:
/* C++ Program - Insert Element in Array */
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int arr[50], size, insert, i, pos;
cout<<"Enter Array Size : ";
cin>>size;
cout<<"Enter array elements : ";
for(i=0; i<size; i++)
{
cin>>arr[i];
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 5
}
cout<<"Enter element to be insert : ";
cin>>insert;
cout<<"At which position (Enter index number) ? ";
cin>>pos;
// now create a space at the required position
for(i=size; i>pos; i--)
0 1 2 3 4
{
arr[i]=arr[i-1];
}
arr[pos]=insert;
cout<<"Element inserted successfully..!!n";
cout<<"Now the new array is : n";
for(i=0; i<size+1; i++)
{
cout<<arr[i]<<" ";
}
getch();
}
 Traversing Linear Arrays:-
Let A be the collection of data elements stored in the memory of the computer. Suppose we want
to print the contents of each element of A or suppose we want to count the number of elements
of A with a given property. This can be accomplished by traversing A that is by accessing and
processing each element of A exactly once.
The following algorithm traverses a linear array LA. The simplicity of the algorithm
comes from the fact that LA is a linear structure. Other linear structures such as linked list can
also be easily traversed. On the other hand the traversal of non-linear structures such as trees and
graphs is considerably more complicated.
Algorithm:-
(Traversing a Linear Array) Here LA is a linear Array with lower
bound LB and upper Bound UB. This algorithm traverses LA
applying an operation PROCESS to each element of LA.
1. [Initialize Counter] Set K=LB.
2. Repeat Step 3 and 4 while K≤UB.//arr[10] for (i=0;i<=9;i++)
3. Cout<<aa[i];
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 6
4. [Visit element] Apply PROCESS to LA[K].
5. [Increase Counter] Set K=K+1.
[End of Step 2 Loop]
6. Exit.
 Deleting Algorithm and code
Let A be a collection of data elements in the memory of computer. “Inserting” refers to the
operation of adding another element to the collection A and “deleting” refers to the operation of
removing one of the elements from A. Here we discuss the inserting and deleting when A is a
linear array.
Inserting an element at the “end” of the linear array can be easily done provided the memory
space allocated for the array is large enough to accommodate the additional element. On the
other hand suppose we need to insert an element in the middle of the array. Then on average half
of the elements must be moved downward to the new location to accommodate the new element
and keep the order of other elements.
Similarly deleting the element at the “end” of an array presents no difficulties but deleting the
element somewhere in the middle of the array would require that each subsequent element be
moved one location upward in order to fill up the array.
Algorithm:-
Algorithm DeleteLA (DATA, N, ITEM, LOC)
Desc: This algorithm deletes an element at Jth position in a linear array DATA with N elements
and stores in ITEM
If LOC=1 it means the element to be deleted is at the beginning
If LOC =N it means the element be deleted is at the end
If LOC = J it means the elements have to be deleted is at at Jth Location
Begin
Step 1: [Initialize counter I with index of element to be deleted]
I=J
Step 2: [Store the element to be deleted in ITEM]
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 7
ITEM=DATA[J]
Step 3: While I<N repeat steps 4 and 5
Step 4: [Move the current element one position forward]
DATA[I]=DATA[I+1]
Step 5: [Increment counter I]
I=I+1
Step 6: [Update total under of array elements]
N=N-1
Exit
Code:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int arr[50], size, i, del, count=0;
cout<<"Enter array size : ";
cin>>size;
cout<<"Enter array elements : ";
for(i=0; i<size; i++)
{
cin>>arr[i];
}
cout<<"Enter element to be delete : ";
cin>>del;
for(i=0; i<size; i++)
{
if(arr[i]==del)
{
for(int j=i; j<(size-1); j++)
{
arr[j]=arr[j+1];
}
count++;
break;
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 8
}
}
if(count==0)
{
cout<<"Element not found..!!";
}
else
{
cout<<"Element deleted successfully..!!n";
cout<<"Now the new array is :n";
for(i=0; i<(size-1); i++)
{
cout<<arr[i]<<" ";
}
}
getch();
}
Searching Algorithms:-
Let DATA be a collection of data elements in memory and suppose a specific ITEM of
information is given. Searching refers to the operation of finding the LOC of the ITEM in DATA
or printing some message that item does not appears there. The searching is said to be successful
if ITEM does not appear in DATA and unsuccessful otherwise.
Frequently one may want to add the element ITEM to DATA after an unsuccessful search for
ITEM in DATA. One then uses a search and insertion algorithm rather than simply a search
algorithm.
There are many different search algorithms. The algorithms that one chooses generally depends
on the way that information in DATA is organized.
Linear Search:-
Suppose DATA is a linear array with n elements. Given no other information about DATA the
most intuitive way to search for a given ITEM in DATA is to compare ITEM with each element
of DATA one by one. That is first we test whether DATA[1] = ITEM and then we test whether
DATA[2] = ITEM and so on. This method which traverses DATA sequentially to locate ITEM is
called linear search of sequential search.
Algorithm:-
(Linear Search) LINEAR(DATA,N,ITEM,LOC)
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 9
Here DATA is a linear array with N elements and ITEM is a given
item of information. This algorithm finds the location LOC of
ITEM in DATA or sets LOC = 0 if the search is unsuccessful.
1. [Insert ITEM at the end of DATA] Set DATA[N+1] = ITEM.
2. Initialize Counter Set LOC = 1.
3. [Search for ITEM]
Repeat while DATA[LOC] ≠ ITEM
SET LOC = LOC+1.
[End of Loop]
4. [Successful?] If LOC = N+1 then Set LOC = 0.
5. Exit.
Code
#include<iostream>
#include<stdlib.h>//header file to use random function
using namespace std;
int main()
{
int arr[100],s,k=0;
for(int i=0;i<100;i++)
{
arr[i]=rand()%100;//assigning 100 random values to an array
cout<<"array["<<i<<"]"<<arr[i]<<endl; //displaying array
}
cout<<"enter a value to search in array:";
cin>>s;// enter value for searching
for(int j=0;j<100;j++)
{
if(s==arr[j]) //applying linear search on array which will check one by one
each index an array
{
cout<<"number found at array["<<j<<"]"<<endl;// print location
k=1;
}
}
if(k==0)//if value is not present then ‘if’ case will execute
{
cout<<"number not found"<<endl;
}
}
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 10
Binary Search:-
Suppose DATA is an array which is sorted in increasing numerical order or equivalently
alphabetically. Then there is an extremely efficient search algorithm called binary search which
can be used to find the location LOC of a given ITEM of information in DATA. Before formally
discussing the algorithm we indicate the general idea of this algorithm by means of an idealized
version of a familiar everyday example.
Suppose one wants to find the location of some name in a telephone directory. Obviously
one does not perform a linear search. Rather one opens the directory in the middle to determine
which half contain the name being sought. Then opens that half in the middle to determine which
quarter of the directory contain the name. Then one opens that quarter in the middle to determine
which eighth of the directory contain the name. And so on. Eventually one finds the location of
the name since one is reducing the number of possible locations for it in the directory.
The binary search algorithm applied to our DATA works as follows. During each stage of our
algorithm our search for ITEM is reduced to a segment of elements of DATA.
DATA[BEG] , DATA[BEG+1] , . . . . . . DATA[END]
Note that the variables BEG and END denote respectively the beginning and end location of the
segment under consideration. The algorithm compares ITEM with the middle element
DATA[MID] of the segment where MID is obtained by.
MID = INT((BEG+END)/2)
(INT(A) is used for the integer value of A) If DATA[MID] = ITEM then the search is successful
and we set the LOC = MID otherwise a new segment of DATA is obtained as follow.
a. If ITEM < DATA[MID] then ITEM can appear only in the left
half of the segment.
DATA[BEG] ,DATA[BEG+1], . . . . . DATA[MID-1]
So we reset END = MID-1 and then begin searching.
b. If ITEM > DATA [MID] then ITEM can appear only in the right
half of the segment.
DATA[MID+1], DATA[MID+2], . . . . . DATA[END]
So we reset BEG = MID+1 and then begin searching.
Initially we begin with entire array DATA i.e. we begin with BEG=1 and END=n or more
generally with BEG=LB and END=UB.
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 11
If ITEM is not in the DATA then eventually we obtain
END<BEG
This condition signals that the search is unsuccessful and in such a case we assign LOC=NULL.
Here NULL is a value that lies outside the set of indices of DATA.
We state the binary search algorithm formally.
Algorithm:-
(Binary Search) BINARY(DATA,UB,LB,ITEM,LOC)
Here DATA is a sorted array with lower bound LB and upper bound
UB and ITEM is a given item of information. The variables BEG,
END, MID denotes respectively the beginning end and middle
location of a segment of elements of DATA. This algorithm finds
the location LOC of ITEM in DATA or sets LOC=NULL.
1. [Initialize Segment Variables]
Set BEG=LB, END=UB and MID= INT((BEG+END)/2)
2. Repeat Step 3 and 4 while BEG≤END and DATA[MID]≠ITEM
3. If ITEM < DATA[MID] then
Set END=MID-1.
else
Set BEG=MID+1.
[End of if Structure]
4. Set MID=INT((BEG+END)/2)
[End of Step 2 Loop]
5. If DATA[MID] = ITEM then
Set LOC=MID
else
Set LOC=NULL
[End of If structure]
6. Exit.
When ITEM does not appear in the DATA then the algorithm eventually arrives at the stage that
BEG=END=MID. Then the next step yield END<BEG and control transfers to Step 5 of the
algorithm.
Sorting Arrays:-
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 12
The process of arranging data in a specified order is called sorting. Numeric type data may be
arranged either in ascending or in descending order. Similarly character type data may be
arranged in alphabetical order.
There are different methods to sort data into a list. The most commonly used methods are:
1. Bubble Sort
2. Selection Sort
Bubble Sort:-
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be
sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
First pass bubble out the largest element and places in the last position and second pass place the
second largest in the second last position and so on. Thus, in the last pass smallest items is placed
in the first position. Because, it only uses comparisons to operate on elements, it is a comparison
sort.
Example:-
Let us take the array of numbers "5 1 4 2 9", and sort the array from lowest number to greatest
number using bubble sort algorithm. In each step, elements written in bold are being compared.
First Pass: Considering length n
( 5 1 4 2 9 ) ⟶ ( 1 5 4 2 9 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 9 ) ⟶ ( 1 4 5 2 9 ), Swap since 5 > 4
( 1 4 5 2 9 ) ⟶ ( 1 4 2 5 9 ), Swap since 5 > 2
( 1 4 2 5 9 ) ⟶ ( 1 4 2 5 9 ), Now, since these elements are already in order (9 > 5), algorithm
does not swap them.
Second Pass: Considering length n - 1
( 1 4 2 5 9 ) ⟶ ( 1 4 2 5 9 )
( 1 4 2 5 9 ) ⟶ ( 1 2 4 5 9 ), Swap since 4 > 2
( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9 )
Third Pass: Considering length n -2
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 13
( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9)
( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9 )
Fourth Pass: Considering length n -3
( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9 )
Example 4:-
Sort the following array:-
{6, 1, 2, 3, 4, 5}
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 14
We formally state the bubble sort algorithm.
Algorithm:-
(Bubble Sort) Bubble (Data, N)
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 15
Here Data is an array with N elements. This algorithm sorts the
elements in DATA.
1. Repeat Step 2 and 3 for K= 1 to N-1.
2. Set PTR=1. [Initialize pass pointer P].
3. Repeat while PTR ≤ N – K [Executes pass]
a. If DATA[PTR]>DATA[PTR+1] then
Interchange DATA[PTR] and DATA[PTR+1].
[End of If structure]
b. Set PTR = PTR +1.
[End of inner Loop]
[End of Step 1 outer Loop]
4. Exit.
Code
#include<iostream>
using namespace std;
int main ()
{
int i, j,temp,pass=0;
int a[10] = {10,2,0,14,43,25,18,1,5,45};
cout <<"Input list ...n";
for(i = 0; i<10; i++) {
cout <<a[i]<<"t";
}
cout<<endl;
for(i = 0; i<10; i++) {
for(j = i+1; j<10; j++)
{
if(a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
pass++;
}
cout <<"Sorted Element List ...n";
for(i = 0; i<10; i++) {
cout <<a[i]<<"t";
}
cout<<"nNumber of passes taken to sort the list:"<<pass<<endl;
return 0;
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 16
}
Selection Sort:-
Selection sort is also a simple a comparison sorting algorithm. The algorithm works as follows:
Algorithm:-
1. 1st iteration selects the smallest element in the array, and swaps it with the first element.
2. 2nd iteration selects the 2nd smallest element (which is the smallest element of the remaining
elements) and swaps it with the 2nd element.
3. The algorithm continues until the last iteration selects the 2nd largest element and swaps it
with the 2nd last index, leaving the largest element in the last index.
Effectively, the list is divided into two parts: the sub list of items already sorted, which is built up
from left to right and is found at the beginning, and the sub list of items remaining to be sorted,
occupying the remainder of the array.
Here is an example of this sort algorithm sorting five elements:
66 25 12 22 11
11 25 12 22 66
11 12 25 22 66
11 12 22 25 66
11 12 22 25 66
Example 5:-
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 17
Algo:
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
/* check the element to be minimum */
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
/* swap the minimum element with the current element*/
if indexMin != i then
swap list[min] and list[i]
end if
end for
end procedure
Task: Write code for selection sort And then implement the
binary search to search a user enter number.
UNIVERSITY OF ENGINEERING AND TECHNOLOGY,TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk
CS201: Data Structures and Algorithms Page 18
Merge Sort
Mergesort(Passed an array)
if array size > 1
Divide array in half
Call Mergesort on first half.
Call Mergesort on second half.
Merge two halves.
Merge(Passed two arrays)
Compare leading element in each array
Select lower and place in new array.
(If one input array is empty then place
remainder of other array in output array)
Task: Write a code to implement the merge sort.
Home Task: Write an algo for quick sort and then write its code.

Updated Lab3.docx

  • 1.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 1 CS201: Data Structure and Algorithms Class: BSCS-2k19 Lab 1: Basic concepts in C++ Date: October 12, 2021 Time: 1200 to 1500 Instructor: Marriam Nawaz marriam.nawaz@uettaxila.edu.pk Lab Manual 03
  • 2.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 2 Lab Manual 3 Introduction This lab is about the Operations on Arrays in C++. Objectives The objectives of this session is to understand the various operations on arrays in C++. Tools/Software Requirement Dev C++ Goals for today’s lab:  Understanding array operations and write it’s algorithm.  Convert algorithm to practical implementation.
  • 3.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 3 Basic concepts What is menat by Data Structure? Organization of information so that machines and humans can better understand it. What is an algorithm? Sequence of steps to solve a particluer problem. Types of Data Strucure (Liner, non-linear) Operation you can perform on data  Insetion  Deletion  Traversing  Searching  sorting Linear Data structure 1. Arrays: collection of similar data items.
  • 4.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 4 Opertion on Arrays  Insertion Algortithm and code Algorithm InsertLA (DATA, N, ITEM, LOC) Desc: This algorithm inserts new element ITEMin linear array DATA with N elements If LOC=1 it means the element has to insert in beginning If LOC =N+1 it means the element have to be inserted at the end If LOC = J it means the elements have to be inserted at Jth Location Begin Step 1: [Initialize counter I with index of last element] I=N Step 2: While I>=LOC repeat steps 3 and 4 Step 3: [Move the current element one position backwards] DATA[I+1]=DATA[I] Step 4: [Decrement counter I] I=I-1 Step 5:[Insert new element at the Location] DATA[LOC]=ITEM Step 6:[ Update total under of array elements] N=N+1 Exit Code: /* C++ Program - Insert Element in Array */ #include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[50], size, insert, i, pos; cout<<"Enter Array Size : "; cin>>size; cout<<"Enter array elements : "; for(i=0; i<size; i++) { cin>>arr[i];
  • 5.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 5 } cout<<"Enter element to be insert : "; cin>>insert; cout<<"At which position (Enter index number) ? "; cin>>pos; // now create a space at the required position for(i=size; i>pos; i--) 0 1 2 3 4 { arr[i]=arr[i-1]; } arr[pos]=insert; cout<<"Element inserted successfully..!!n"; cout<<"Now the new array is : n"; for(i=0; i<size+1; i++) { cout<<arr[i]<<" "; } getch(); }  Traversing Linear Arrays:- Let A be the collection of data elements stored in the memory of the computer. Suppose we want to print the contents of each element of A or suppose we want to count the number of elements of A with a given property. This can be accomplished by traversing A that is by accessing and processing each element of A exactly once. The following algorithm traverses a linear array LA. The simplicity of the algorithm comes from the fact that LA is a linear structure. Other linear structures such as linked list can also be easily traversed. On the other hand the traversal of non-linear structures such as trees and graphs is considerably more complicated. Algorithm:- (Traversing a Linear Array) Here LA is a linear Array with lower bound LB and upper Bound UB. This algorithm traverses LA applying an operation PROCESS to each element of LA. 1. [Initialize Counter] Set K=LB. 2. Repeat Step 3 and 4 while K≤UB.//arr[10] for (i=0;i<=9;i++) 3. Cout<<aa[i];
  • 6.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 6 4. [Visit element] Apply PROCESS to LA[K]. 5. [Increase Counter] Set K=K+1. [End of Step 2 Loop] 6. Exit.  Deleting Algorithm and code Let A be a collection of data elements in the memory of computer. “Inserting” refers to the operation of adding another element to the collection A and “deleting” refers to the operation of removing one of the elements from A. Here we discuss the inserting and deleting when A is a linear array. Inserting an element at the “end” of the linear array can be easily done provided the memory space allocated for the array is large enough to accommodate the additional element. On the other hand suppose we need to insert an element in the middle of the array. Then on average half of the elements must be moved downward to the new location to accommodate the new element and keep the order of other elements. Similarly deleting the element at the “end” of an array presents no difficulties but deleting the element somewhere in the middle of the array would require that each subsequent element be moved one location upward in order to fill up the array. Algorithm:- Algorithm DeleteLA (DATA, N, ITEM, LOC) Desc: This algorithm deletes an element at Jth position in a linear array DATA with N elements and stores in ITEM If LOC=1 it means the element to be deleted is at the beginning If LOC =N it means the element be deleted is at the end If LOC = J it means the elements have to be deleted is at at Jth Location Begin Step 1: [Initialize counter I with index of element to be deleted] I=J Step 2: [Store the element to be deleted in ITEM]
  • 7.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 7 ITEM=DATA[J] Step 3: While I<N repeat steps 4 and 5 Step 4: [Move the current element one position forward] DATA[I]=DATA[I+1] Step 5: [Increment counter I] I=I+1 Step 6: [Update total under of array elements] N=N-1 Exit Code: #include<iostream.h> #include<conio.h> void main() { clrscr(); int arr[50], size, i, del, count=0; cout<<"Enter array size : "; cin>>size; cout<<"Enter array elements : "; for(i=0; i<size; i++) { cin>>arr[i]; } cout<<"Enter element to be delete : "; cin>>del; for(i=0; i<size; i++) { if(arr[i]==del) { for(int j=i; j<(size-1); j++) { arr[j]=arr[j+1]; } count++; break;
  • 8.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 8 } } if(count==0) { cout<<"Element not found..!!"; } else { cout<<"Element deleted successfully..!!n"; cout<<"Now the new array is :n"; for(i=0; i<(size-1); i++) { cout<<arr[i]<<" "; } } getch(); } Searching Algorithms:- Let DATA be a collection of data elements in memory and suppose a specific ITEM of information is given. Searching refers to the operation of finding the LOC of the ITEM in DATA or printing some message that item does not appears there. The searching is said to be successful if ITEM does not appear in DATA and unsuccessful otherwise. Frequently one may want to add the element ITEM to DATA after an unsuccessful search for ITEM in DATA. One then uses a search and insertion algorithm rather than simply a search algorithm. There are many different search algorithms. The algorithms that one chooses generally depends on the way that information in DATA is organized. Linear Search:- Suppose DATA is a linear array with n elements. Given no other information about DATA the most intuitive way to search for a given ITEM in DATA is to compare ITEM with each element of DATA one by one. That is first we test whether DATA[1] = ITEM and then we test whether DATA[2] = ITEM and so on. This method which traverses DATA sequentially to locate ITEM is called linear search of sequential search. Algorithm:- (Linear Search) LINEAR(DATA,N,ITEM,LOC)
  • 9.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 9 Here DATA is a linear array with N elements and ITEM is a given item of information. This algorithm finds the location LOC of ITEM in DATA or sets LOC = 0 if the search is unsuccessful. 1. [Insert ITEM at the end of DATA] Set DATA[N+1] = ITEM. 2. Initialize Counter Set LOC = 1. 3. [Search for ITEM] Repeat while DATA[LOC] ≠ ITEM SET LOC = LOC+1. [End of Loop] 4. [Successful?] If LOC = N+1 then Set LOC = 0. 5. Exit. Code #include<iostream> #include<stdlib.h>//header file to use random function using namespace std; int main() { int arr[100],s,k=0; for(int i=0;i<100;i++) { arr[i]=rand()%100;//assigning 100 random values to an array cout<<"array["<<i<<"]"<<arr[i]<<endl; //displaying array } cout<<"enter a value to search in array:"; cin>>s;// enter value for searching for(int j=0;j<100;j++) { if(s==arr[j]) //applying linear search on array which will check one by one each index an array { cout<<"number found at array["<<j<<"]"<<endl;// print location k=1; } } if(k==0)//if value is not present then ‘if’ case will execute { cout<<"number not found"<<endl; } }
  • 10.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 10 Binary Search:- Suppose DATA is an array which is sorted in increasing numerical order or equivalently alphabetically. Then there is an extremely efficient search algorithm called binary search which can be used to find the location LOC of a given ITEM of information in DATA. Before formally discussing the algorithm we indicate the general idea of this algorithm by means of an idealized version of a familiar everyday example. Suppose one wants to find the location of some name in a telephone directory. Obviously one does not perform a linear search. Rather one opens the directory in the middle to determine which half contain the name being sought. Then opens that half in the middle to determine which quarter of the directory contain the name. Then one opens that quarter in the middle to determine which eighth of the directory contain the name. And so on. Eventually one finds the location of the name since one is reducing the number of possible locations for it in the directory. The binary search algorithm applied to our DATA works as follows. During each stage of our algorithm our search for ITEM is reduced to a segment of elements of DATA. DATA[BEG] , DATA[BEG+1] , . . . . . . DATA[END] Note that the variables BEG and END denote respectively the beginning and end location of the segment under consideration. The algorithm compares ITEM with the middle element DATA[MID] of the segment where MID is obtained by. MID = INT((BEG+END)/2) (INT(A) is used for the integer value of A) If DATA[MID] = ITEM then the search is successful and we set the LOC = MID otherwise a new segment of DATA is obtained as follow. a. If ITEM < DATA[MID] then ITEM can appear only in the left half of the segment. DATA[BEG] ,DATA[BEG+1], . . . . . DATA[MID-1] So we reset END = MID-1 and then begin searching. b. If ITEM > DATA [MID] then ITEM can appear only in the right half of the segment. DATA[MID+1], DATA[MID+2], . . . . . DATA[END] So we reset BEG = MID+1 and then begin searching. Initially we begin with entire array DATA i.e. we begin with BEG=1 and END=n or more generally with BEG=LB and END=UB.
  • 11.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 11 If ITEM is not in the DATA then eventually we obtain END<BEG This condition signals that the search is unsuccessful and in such a case we assign LOC=NULL. Here NULL is a value that lies outside the set of indices of DATA. We state the binary search algorithm formally. Algorithm:- (Binary Search) BINARY(DATA,UB,LB,ITEM,LOC) Here DATA is a sorted array with lower bound LB and upper bound UB and ITEM is a given item of information. The variables BEG, END, MID denotes respectively the beginning end and middle location of a segment of elements of DATA. This algorithm finds the location LOC of ITEM in DATA or sets LOC=NULL. 1. [Initialize Segment Variables] Set BEG=LB, END=UB and MID= INT((BEG+END)/2) 2. Repeat Step 3 and 4 while BEG≤END and DATA[MID]≠ITEM 3. If ITEM < DATA[MID] then Set END=MID-1. else Set BEG=MID+1. [End of if Structure] 4. Set MID=INT((BEG+END)/2) [End of Step 2 Loop] 5. If DATA[MID] = ITEM then Set LOC=MID else Set LOC=NULL [End of If structure] 6. Exit. When ITEM does not appear in the DATA then the algorithm eventually arrives at the stage that BEG=END=MID. Then the next step yield END<BEG and control transfers to Step 5 of the algorithm. Sorting Arrays:-
  • 12.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 12 The process of arranging data in a specified order is called sorting. Numeric type data may be arranged either in ascending or in descending order. Similarly character type data may be arranged in alphabetical order. There are different methods to sort data into a list. The most commonly used methods are: 1. Bubble Sort 2. Selection Sort Bubble Sort:- Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. First pass bubble out the largest element and places in the last position and second pass place the second largest in the second last position and so on. Thus, in the last pass smallest items is placed in the first position. Because, it only uses comparisons to operate on elements, it is a comparison sort. Example:- Let us take the array of numbers "5 1 4 2 9", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared. First Pass: Considering length n ( 5 1 4 2 9 ) ⟶ ( 1 5 4 2 9 ), Here, algorithm compares the first two elements, and swaps them. ( 1 5 4 2 9 ) ⟶ ( 1 4 5 2 9 ), Swap since 5 > 4 ( 1 4 5 2 9 ) ⟶ ( 1 4 2 5 9 ), Swap since 5 > 2 ( 1 4 2 5 9 ) ⟶ ( 1 4 2 5 9 ), Now, since these elements are already in order (9 > 5), algorithm does not swap them. Second Pass: Considering length n - 1 ( 1 4 2 5 9 ) ⟶ ( 1 4 2 5 9 ) ( 1 4 2 5 9 ) ⟶ ( 1 2 4 5 9 ), Swap since 4 > 2 ( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9 ) Third Pass: Considering length n -2
  • 13.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 13 ( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9) ( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9 ) Fourth Pass: Considering length n -3 ( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9 ) Example 4:- Sort the following array:- {6, 1, 2, 3, 4, 5}
  • 14.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 14 We formally state the bubble sort algorithm. Algorithm:- (Bubble Sort) Bubble (Data, N)
  • 15.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 15 Here Data is an array with N elements. This algorithm sorts the elements in DATA. 1. Repeat Step 2 and 3 for K= 1 to N-1. 2. Set PTR=1. [Initialize pass pointer P]. 3. Repeat while PTR ≤ N – K [Executes pass] a. If DATA[PTR]>DATA[PTR+1] then Interchange DATA[PTR] and DATA[PTR+1]. [End of If structure] b. Set PTR = PTR +1. [End of inner Loop] [End of Step 1 outer Loop] 4. Exit. Code #include<iostream> using namespace std; int main () { int i, j,temp,pass=0; int a[10] = {10,2,0,14,43,25,18,1,5,45}; cout <<"Input list ...n"; for(i = 0; i<10; i++) { cout <<a[i]<<"t"; } cout<<endl; for(i = 0; i<10; i++) { for(j = i+1; j<10; j++) { if(a[j] < a[i]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } pass++; } cout <<"Sorted Element List ...n"; for(i = 0; i<10; i++) { cout <<a[i]<<"t"; } cout<<"nNumber of passes taken to sort the list:"<<pass<<endl; return 0;
  • 16.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 16 } Selection Sort:- Selection sort is also a simple a comparison sorting algorithm. The algorithm works as follows: Algorithm:- 1. 1st iteration selects the smallest element in the array, and swaps it with the first element. 2. 2nd iteration selects the 2nd smallest element (which is the smallest element of the remaining elements) and swaps it with the 2nd element. 3. The algorithm continues until the last iteration selects the 2nd largest element and swaps it with the 2nd last index, leaving the largest element in the last index. Effectively, the list is divided into two parts: the sub list of items already sorted, which is built up from left to right and is found at the beginning, and the sub list of items remaining to be sorted, occupying the remainder of the array. Here is an example of this sort algorithm sorting five elements: 66 25 12 22 11 11 25 12 22 66 11 12 25 22 66 11 12 22 25 66 11 12 22 25 66 Example 5:-
  • 17.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 17 Algo: procedure selection sort list : array of items n : size of list for i = 1 to n - 1 /* set current element as minimum*/ min = i /* check the element to be minimum */ for j = i+1 to n if list[j] < list[min] then min = j; end if end for /* swap the minimum element with the current element*/ if indexMin != i then swap list[min] and list[i] end if end for end procedure Task: Write code for selection sort And then implement the binary search to search a user enter number.
  • 18.
    UNIVERSITY OF ENGINEERINGAND TECHNOLOGY,TAXILA DEPARTMENT OF COMPUTER SCIENCE http://web.uettaxila.edu.pk CS201: Data Structures and Algorithms Page 18 Merge Sort Mergesort(Passed an array) if array size > 1 Divide array in half Call Mergesort on first half. Call Mergesort on second half. Merge two halves. Merge(Passed two arrays) Compare leading element in each array Select lower and place in new array. (If one input array is empty then place remainder of other array in output array) Task: Write a code to implement the merge sort. Home Task: Write an algo for quick sort and then write its code.