0% found this document useful (0 votes)
24 views19 pages

DS Unit I

The document discusses data structures and algorithms. It defines key terms like data types, data structures, abstract data types, algorithms and their properties. It describes linear and nonlinear data structures as well as common operations on data structures like traversing, searching, inserting and deleting. It also discusses different categories of algorithms and ways to analyze algorithm performance.

Uploaded by

kolavennela90
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)
24 views19 pages

DS Unit I

The document discusses data structures and algorithms. It defines key terms like data types, data structures, abstract data types, algorithms and their properties. It describes linear and nonlinear data structures as well as common operations on data structures like traversing, searching, inserting and deleting. It also discusses different categories of algorithms and ways to analyze algorithm performance.

Uploaded by

kolavennela90
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/ 19

Unit - 1 Data Structures and Algorithms

UNIT I
Basic concepts - Data types, Abstract Data Types, Data structures, Algorithms.
Searching- Linear Search, Binary Search
Sorting- Bubble Sort, Insertion Sort, Selection Sort, Quick sort, Merge sort, Comparison of
Sorting methods.

Data Structures
 Data may be organized in many different ways logical or mathematical model of a program
particularly organization of data. This organized data is called “Data Structure”.
 Or
 The organized collection of data is called a ‘Data Structure’.

Data Structure=Organized data +Allowed operations

Data Structure involves two complementary goals.


1. The first goal is to identify and develop useful, mathematical entities and operations
and to determine what class of problems can be solved by using these entities and
operations.
2. The second goal is to determine representation for those abstract entities to
implement abstract operations on this concrete representation.

Data Types
 Primitive Data types are directly supported by the language (ie) any operation is directly
performed in these data items.
o Ex: integer, Character, Real numbers etc.

 Non-primitive data types are not defined by the programming language, but are instead
created by the programmer.
1. Linear data structures organize their data elements in a linear fashion, where data
elements are attached one after the other. Linear data structures are very easy to
implement, since the memory of the computer is also organized in a linear fashion.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Some commonly used linear data structures are arrays, linked lists, stacks and
queues.
2. In nonlinear data structures, data elements are not organized in a sequential fashion.
Data structures like multidimensional arrays, trees, graphs, tables and sets are some
examples of widely used nonlinear data structures.

Operations on the Data Structures:


Following operations can be performed on the data structures:
1. Traversing- It is used to access each data item exactly once so that it can be processed.
2. Searching- It is used to find out the location of the data item if it exists in the given
collection of data items.
3. Inserting- It is used to add a new data item in the given collection of data items.
4. Deleting- It is used to delete an existing data item from the given collection of data items.
5. Sorting- It is used to arrange the data items in some order i.e. in ascending or descending
order in case of numerical data and in dictionary order in case of alphanumeric data.
6. Merging- It is used to combine the data items of two sorted files into single file in the sorted
form.

Abstract Data Type


 In computer science, an abstract data type (ADT) is a mathematical model for data
types where a data type is defined by its behavior (semantics) from the point of view
of a user of the data, specifically in terms of possible values, possible operations on
data of this type, and the behavior of these operations.
 When a class is used as a type, it is an abstract type that refers to a hidden
representation. In this model an ADT is typically implemented as a class, and each
instance of the ADT is usually an object of that class.
 In ADT all the implementation details are hidden.

Algorithm
Definition: -
An algorithm is a Step By Step process to solve a problem, where each step indicates an
intermediate task. Algorithm contains finite number of steps that leads to the solution of the
problem.

Properties /Characteristics of an Algorithm:-


Algorithm has the following basic properties
 Input-Output:- Algorithm takes ‘0’ or more input and produces the required output.
This is the basic characteristic of an algorithm.
 Finiteness:- An algorithm must terminate in countable number of steps.
 Definiteness: Each step of an algorithm must be stated clearly and unambiguously.
 Effectiveness: Each and every step in an algorithm can be converted in to programming
language statement.
 Generality: Algorithm is generalized one. It works on all set of inputs and provides the
required output. In other words it is not restricted to a single input value.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Categories of Algorithm:
Based on the different types of steps in an Algorithm, it can be divided into three categories,
namely
 Sequence
 Selection and
 Iteration

Sequence:
 The steps described in an algorithm are performed successively one by one without
skipping any step.
 The sequence of steps defined in an algorithm should be simple and easy to understand.
 Each instruction of such an algorithm is executed, because no selection procedure or
conditional branching exists in a sequence algorithm.
Example:
// adding two numbers
Step 1: start
Step 2: read a,b
Step 3: Sum=a+b
Step 4: write Sum
Step 5: stop

Selection:
 The sequence type of algorithms are not sufficient to solve the problems, which involves decision
and conditions. In order to solve the problem which involve decision making or option selection,
we go for Selection type of algorithm.
 The general format of Selection type of statement is as shown below:
if(condition)
Statement-1;
else
Statement-2;

 The above syntax specifies that if the condition is true, statement-1 will be executed otherwise
statement-2 will be executed. In case the operation is unsuccessful.
 Then sequence of algorithm should be changed/ corrected in such a way that the system will re-
execute until the operation is successful.

 Iteration: Iteration type algorithms are used in solving the problems which involves
repetition of statement.
 In this type of algorithms, a particular number of statements are repeated ‘n’ no. of times.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Example:
Step 1 : start
Step 2 : read n
Step 3 : repeat
step 4 : until n>0
(a) r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step 6 : stop

Performance Analysis an Algorithm:


The Efficiency of an Algorithm can be measured by the following metrics.
i. Time Complexity:
 The amount of time required for an algorithm to complete its execution is its time
complexity.
 An algorithm is said to be efficient if it takes the minimum (reasonable) amount
of time to complete its execution.
ii. Space Complexity:
 The amount of space occupied by an algorithm is known as Space Complexity.
 An algorithm is said to be efficient if it occupies less space and required the
minimum amount of time to complete its execution.
**************
Searching
• Searching is a process of finding a particular element among several given elements.
• The search is successful if the required element is found.
• Otherwise, the search is unsuccessful.
Searching Algorithms-
The searching of an element in the given array may be carried out in the following two ways-

1.Linear Search
• Linear search, the simplest search algorithm, is mainly used to find the element from
an unordered list.
• It is also known by another name called sequential search algorithm. In linear search,
the list is simply traversed, and each element in the list is matched with the element whose
location needs to be found.
• When the searching process is done, it returns the location of the element, else the
algorithm returns NULL.

Ex: consider the following Array A


23 15 18 17 42 96 103
 Now let us search for 17 by Linear search. The searching starts from the first
position. Since A[0] ≠17.
 The search proceeds to the next position i.e; second position A[1] ≠17.
 The above process continuous until the search element is found such as A[3]=17. Here
the searching element is found in the position 4.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C implementation for Linear Search


#include <stdio.h>
int main()
{
int i,size,a[10],search,flag=0;
printf("\n Enter the size of an array :");
scanf("%d",&size);
printf("\n Enter the value :");
for(i=0;i<size;i++)
scanf("%d",&a[i]);
printf("\n Find the search element : ");
scanf("%d",&search);

for(i=0;i<size;i++)
{
if(search==a[i])
{
flag=1;
break;
}
}
if (flag==1)
printf("%d fount at the position %d ",search,mid+1);
else
printf("element not found");
return 0;
}
Advantages:
It is simplest known technique.
The elements in the list can be in any order.
Disadvantages:
This method is in efficient when large numbers of elements are present in list because time
taken for searching is more.
Complexity of Linear Search: The worst and average case complexity of Linear search is
O(n), where ‘n’ is the total number of elements present in the list.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Binary Search
 Binary Search is one of the fastest searching algorithms.
 It is used for finding the location of an element in a linear array.
 It works on the principle of divide and conquer technique.
 Binary Search Algorithm can be applied only on Sorted arrays.(Ascending Order)
 So, the elements must be arranged in Either ascending order if the elements are numbers Or
dictionary order if the elements are strings.
 To apply binary search on an unsorted array,First, sort the array using some sorting
technique.Then, use binary search algorithm.

Binary Search Algorithm-


Hints:
 There is a linear array ‘a’ of size ‘n’.(sorted order)
 Find mid =(start+stop)/2
 Case 1 : Search==a[mid] then element found
 Case 2 : Search < a[mid] . Stop = mid-1
 Case 3 : Search > a[mid]  Start = mid +1

C CODE FOR BINARY SEARCH:


#include <stdio.h>
int main()
{
int i,size,a[10],search,start,mid,stop,flag=0;
printf("\n Enter the size of an array :");
scanf("%d",&size);

printf("\n Enter the value (ascending order) :");


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

printf("\n Find the search element : ");


scanf("%d",&search);

start=0;
stop=size-1;

while(start<=stop)
{
mid=(start+stop)/2;
if(search==a[mid])
{
flag=1;
break;
}
else if (search<a[mid])
stop=mid-1;
else
start=mid+1;
}
if(flag==1)
printf("%d fount at the position %d ",search,mid+1);
else
printf("element not found");
return 0;
}

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

The advantages of binary search algorithm are-


 It is a much faster algorithm.
 It works on divide and conquers principle.
 It eliminates half of the list from further searching by using the result of each comparison.
The disadvantages of binary search algorithm are-
 It can be used only when data is sorted.
 It is more complicated.
 Random access is not supported.
Example:

Time Complexity Analysis-


Best case : O(1)
Worst Case and average case : O(log n).
***********
SORTING
A sorting algorithm is used to arrange elements of an array/list in a specific order.

Types of Sorting
1.Bubble Sort
2.Selection Sort
3.Insertion Sort
4.Merge Sort
5.Quick Sort

1. BUBBLE SORT
 Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until
they are in the intended order.
 Just like the movement of air bubbles in the water that rise up to the surface, each element of
the array move to the end in each iteration.
 Therefore, it is called a bubble sort.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Algorithm :
Step 0 : Initialize n to length of the array
Step 1 : Initialize j to 0 and compare a[j] with a[j+1] (compare adjacent elements starting
from 0th index)
Step 2 : if a[j] > a[j+1] swap a[j] and a[j+1]
Step 3 : repeat steps 1 and 2 until j reached end of the array ( by end of this one element will
be placed at its correct order )
Step 4 : continue from Step 1 n-1 times ( so that all elements will be in proper order)

Example:

C CODE FOR BUBBLE SORT :


#include <stdio.h>
int main()
{
int a[50],n,i,j,temp;

printf("Enter Size of an Array :");


scanf("%d",&n);

printf("Values are");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Ascending Order Using Bubble Sort \n");
for(i=0;i<n;i++)
printf("\t %d",a[i]);
return 0;
}

OUTPUT

Enter Size of an Array :8


Values are
25 57 48 37 12 92 86 33
Ascending Order Using Bubble Sort 12 25 33 37 48 57 86 92
*********
2. SELECTION SORT
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from the unsorted part and putting it at the beginning.
Algorithm :
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.
Example

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C CODE FOR SELECTION SORT :


#include <stdio.h>
int main()
{
int a[100], n, i, j, min,temp;

printf("Enter number of elements \n");


scanf("%d", &n);

printf("Enter Values");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);

for(i = 0; i < n - 1; i++)


{
min=i;
for(j = i + 1; j < n; j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
printf("Sorted Array:\n");
for(i = 0; i < n; i++)
printf("%d \n", a[i]);
return 0;
}
OUTPUT
Enter number of elements
5
Enter Values 77 -1 64 234 14
Sorted Array:
-1 14 64 77 234
************

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

INSERTION SORT
 Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in
each iteration.
 Insertion sort is a simple sorting algorithm that works similar to the way you sort playing
cards in your hands
Advantage
o Simple implementation
o Efficient for small data sets
o Adaptive, i.e., it is appropriate for data sets that are already substantially sorted.
Algorithm
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step 2 - Pick the next element, and store it separately in a key.
Step 3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
EXAMPLE :

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C CODE FOR INSERTION:


#include <stdio.h>
int main()
{
int a[100], n, i, j, temp;

printf("\n Enter the total Number of Elements : ");


scanf("%d", &n);

printf("\n Enter the Array Elements : ");


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

for(i = 1; i <= n - 1; i++)


{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
printf("\n Insertion Sort Result : ");
for(i = 0; i < n; i++)
printf(" %d \t", a[i]);

return 0;
}

OUTPUT
Enter the total Number of Elements : 5
Enter the Array Elements : 25
6
97
-1
15
Insertion Sort Result : -1 6 15 25 97
***********
MERGE SORT
 Merge Sort is one of the most popular sorting algorithms that is based on the principle
of Divide and Conquer Algorithm.
 Here, a problem is divided into multiple sub-problems.
 Each sub-problem is solved individually.
 Finally, sub-problems are combined to form the final solution.

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Divide and Conquer Strategy


 Using the Divide and Conquer technique, we divide a problem into sub problems.
 When the solution to each sub problem is ready, we 'combine' the results from the sub
problems to solve the main problem.

Algorithm:
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
Follow the steps below the solve the problem:
MergeSort(arr[], l, r)
If r > l
Find the middle point to divide the array into two halves:
middle m = l + (r – l)/2
Call mergeSort for first half:
Call mergeSort(arr, l, m)
Call mergeSort for second half:
Call mergeSort(arr, m + 1, r)
Merge the two halves sorted in steps 2 and 3:

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Call merge(arr, l, m, r)

C CODE FOR MERGE SORT:


#include<stdio.h>

void partition(int a[ ],int low,int high);


void merge(int a[],int low,int mid, int high);

int main()
{
int a[50],i,j,size,temp,low,high,mid,mi,k;

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


scanf("%d",&size);

printf("Enter array elements: ");


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

partition(a,0,size-1);

printf("\n Sorted array is: ");


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

return 0;
}

void partition(int a[],int low,int high)


{
int mid;
if(low<high)
{
mid=(low+high)/2;
partition(a,low,mid);
partition(a,mid+1,high);
merge(a,low,mid,high);
}
}

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

void merge(int a[],int low,int mid, int high)


{
int lower=low;
int i=low;
int mi=mid+1;
int temp[100],k;

while(lower<=mid&&mi<=high)
{
if(a[lower]<=a[mi])
{
temp[i]=a[lower];
lower++;
}
else
{
temp[i]=a[mi];
mi++;
}
i++;
}
if(lower>mid)
{
for(k=mi;k<=high;k++)
{
temp[i]=a[k];
i++;
}
}
else
{
for(k=lower;k<=mid;k++)
{
temp[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}

OUTPUT :

Enter size of the array: 6

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Enter array elements: 56 -1 15 98 4 69


Sorted array is: -1 4 15 56 69 98
QUICK SORT
1. An array is divided into subarrays by selecting a pivot element (element selected from the
array).
2. While dividing the array, the pivot element should be positioned in such a way that elements
less than pivot are kept on the left side and elements greater than pivot are on the right side
of the pivot.
3. The left and right subarrays are also divided using the same approach. This process
continues until each subarray contains a single element.
4. At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.

EXAMPLE

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

C CODE FOR QUICK SORT :


#include<stdio.h>
void quicksort(int a[25],int first,int last)
{
int i, j, pivot, temp;

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot] && i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
int main()
{
int i, n, a[25];

printf("Enter the total Number of Elements : ");


scanf("%d",&n);

printf("Enter elements: ");


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

quicksort(a,0,n-1);

printf("Order of Sorted elements: ");


for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}

OUTPUT
Enter the total Number of Elements : 5
Enter elements: 12 5 47 11 1
Order of Sorted elements: 1 5 11 12 47

Department of CS & AI, SR University.


Unit - 1 Data Structures and Algorithms

Comparison of Sorting

**************

Department of CS & AI, SR University.

You might also like