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

Sorting and Searching

The document discusses various sorting and searching algorithms as well as data structures like linked lists. It provides details on linear and binary search, sorting methods like bubble sort, selection sort, insertion sort, merge sort and their time complexities. It also discusses internal and external sorting. Linked lists are defined as dynamic data structures where elements are linked using pointers rather than stored contiguously.

Uploaded by

nehavj664
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Sorting and Searching

The document discusses various sorting and searching algorithms as well as data structures like linked lists. It provides details on linear and binary search, sorting methods like bubble sort, selection sort, insertion sort, merge sort and their time complexities. It also discusses internal and external sorting. Linked lists are defined as dynamic data structures where elements are linked using pointers rather than stored contiguously.

Uploaded by

nehavj664
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Sorting and Searching:

•Searching is the process of determining whether or not a given value exists in a data
structure or a storage media.

• Two searching methods are: linear search and binary search.

•The linear (or sequential) search algorithm on an array is:

1. Sequentially scan the array, comparing each array item with the searched value.

2. If a match is found; return the index of the matched element; otherwise return –1.

Sorting:

Arranging the data in ascending or descending order is known as sorting.

Internal Sorting :

When all data is placed in the main memory or internal memory then sorting is
called internal sorting.
In internal sorting, the problem cannot take input beyond its size.
Example: heap sort, bubble sort, selection sort, quick sort, shell sort, insertion sort.

External Sorting :

We can use an external sort when the collection of data cannot fit in the computer’s main
memory all at once but must reside in secondary storage such as on a disk
External Sorting is used for the massive amount of data.
Merge Sort and its variations are typically used for external sorting.
Some external storage like hard disks and CDs are used for external sorting.
Example: Merge sort, Tag sort, Polyphase sort, Four tape sort, External radix sort,
Internal merge sort, etc.

Sort Order :

• Data can be ordered either in ascending order or in descending order

• The order in which the data is organized, either ascending order or descending order, is
called sort order

Sort Stability

• A sorting method is said to be stable if at the end of the method, identical elements occur in
the same relative order as in the original unsorted set

•Sort Efficiency

•Sort efficiency is a measure of the relative efficiency of a sort


Passes

• During the sorted process, the data is traversed many times

• Each traversal of the data is referred to as a sort pass

• In addition, the characteristic of a sort pass is the placement of one or more elements in a
sorted list

Application of sorting

1. The sorting is useful in database applications for arranging the data in desired ORDER.

2. In the dictionary like applications the data is arranged in sorted order.

3. For searching the element from the list of elements the sorting is required

4. For checking the uniqueness of the element the sorting is required.

5. For finding the closest pair from the list of elements the sorting is required.

Bubble sort:
In bubble sorting, consecutive adjacent pairs of elements in the array are compared
with each other. If the element at the lower index is greater than the element at the
higher index, the two elements are interchanged so that the element is placed before
the bigger one. This process will continue till the list of unsorted elements exhausts.
time complexity:

1. Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when
the input array is already sorted)
Space complexity: O(1)
2. Basic idea: Iterate through the array repeatedly, comparing adjacent pairs of
elements and swapping them if they are in the wrong order. Repeat until the array is
fully sorted.

Advantages:

Simple implementation
works well for small datasets
requires only constant space, stable sorting algorithm

Disadvantages:

Inefficient for large datasets


worst-case time complexity of O(n^2)
not optimal for partially sorted datasets

selection sort:
Selection sorting is conceptually the simplest sorting algorithm. This algorithm first
finds the smallest element in the array and exchanges it with the element in the first
position, then finds the second smallest element and exchange it with the element in
the second position, and continues in this way until the entire array is sorted

Complexity Analysis of Selection Sort


Time Complexity: The time complexity of Selection Sort is O(N2) as there are two
nested loops:

One loop to select an element of Array one by one = O(N)


Another loop to compare that element with every other Array element = O(N)
Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N2)

Auxiliary Space: O(1) as the only extra memory used is for temporary variables while
swapping two values in Array. The selection sort never makes more than O(N) swaps and
can be useful when memory writing is costly.

Advantages of Selection Sort Algorithm


Simple and easy to understand.
Works well with small datasets.

Disadvantages of the Selection Sort Algorithm


Selection sort has a time complexity of O(n^2) in the worst and average case.
Does not work well on large datasets.
Does not preserve the relative order of items with equal keys which means it is not
stable.
INSERTION SORT:
Insertion sort inserts each item into its proper place in the final list. In insertion sort ,
the first iteration starts with comparison of 1st element with 0th element. In the second
iteration 2nd element is compared with the 0th and 1st element and so on. In every
iteration an element is compared with all elements.

Example Consider an array of integers given below. We will sort the values in the array
using insertion sort

23 15 29 11 1
Advantages:

The advantages of this sorting algorithm are as follows:

Relatively simple and Easy to implement. o

It is easy to implement and efficient to use on small sets of data.

It can be efficiently implemented on data sets that are already substantially sorted.

The insertion sort is an in-place sorting algorithm so the space requirement is minimal.

Disadvantages: o

Inefficient for large list O (n2).

MERGE SORT
The merge sort recursively follows the steps

: 1) Divide the given array into equal parts.

2) Recursively sorts the elements on the left side of the partitions.

3) Recursively sorts the elements on the right side of the partitions

. 4) Combine the sorted left and right partitions into a single sorted array.
Advantages :

Merge sort algorithm is best case for sorting slow-access data e.g) tape drive

. Merge sort algorithm is better at handling sequential - accessed lists

. Disadvantages:

 Slower comparative to the other sort algorithms for smaller tasks.

 Merge sort algorithm requires additional memory space of 0(n) for the temporary
array .

 It goes through the whole process even if the array is sorted

Complexity of Merge Sort

The running time of merge sort in the average case and the worst case can be given as
O(n logn).

Although merge sort has an optimal Tim complexity, it needs an additional space of
O(n) for the temporary array TEMP.

Applications
 Merge Sort is useful for sorting linked lists in O(nLogn) time.

 Inversion Count Problem  Used in External Sorting.

Shell sort

linked list:
Linked List is a linear data structure, in which elements are not stored at a contiguous
location, rather they are linked using pointers. Linked List forms a series of connected
nodes, where each node stores the data and the address of the next node.Linked List is
a linear data structure, in which elements are not stored at a contiguous location,
rather they are linked using pointers. Linked List forms a series of connected nodes,
where each node stores the data and the address of the next node.

Node Structure: A node in a linked list typically consists of two components:


Data: It holds the actual value or data associated with the node.
Next Pointer: It stores the memory address (reference) of the next node in the
sequence.
Head and Tail: The linked list is accessed through the head node, which points to the
first node in the list. The last node in the list points to NULL or nullptr, indicating the
end of the list. This node is known as the tail node.

Why linked list data structure needed?


Dynamic Data structure: The size of memory can be allocated or de-allocated at run
time based on the operation insertion or deletion.
Ease of Insertion/Deletion: The insertion and deletion of elements are simpler than
arrays since no elements need to be shifted after insertion and deletion, Just the
address needed to be updated.
Efficient Memory Utilization: As we know Linked List is a dynamic data structure the
size increases or decreases as per the requirement so this avoids the wastage of
memory.
Implementation: Various advanced data structures can be implemented using a
linked list like a stack, queue, graph, hash maps, etc

Linked List ADT


structure Linked List (item)

declare CREATE() -> Linked list

insert(item, linked list) -> linked list

delete(linked list) -> linked list

ISEMPS(linked list) -> boolean;

for all L ∈ Linked list, i ∈ item let

ISEMPS(CREATE) ::= true

ISEMPS(insert(i,L)) ::= false

delete(CREATE) ::= error

delete(insert(I,L)) ::= L

end Linked List

Advantages of Linked Lists


Dynamic Size: Linked lists can grow or shrink dynamically, as memory allocation is
done at runtime.
Insertion and Deletion: Adding or removing elements from a linked list is efficient,
especially for large lists.
Flexibility: Linked lists can be easily reorganized and modified without requiring a
contiguous block of memory.

Disadvantages of Linked Lists


Random Access: Unlike arrays, linked lists do not allow direct access to elements by
index. Traversal is required to reach a specific node.
Extra Memory: Linked lists require additional memory for storing the pointers,
compared to arrays.
Difference Between Sequential Organization and Linked Organization:
S.N Linked Organization Sequential Organization

1. Data is stored in nodes Data is stored in a linear


that are linked together sequence

2. Each node contains data Each element is stored


and a pointer to the next one after the other
node

3. Allows for fast insertions Allows for fast traversal


and deletions and access

4. More complex to Simpler to implement


implement

5. Can be used for Can be used for


implementing data implementing data
structures like linked lists structures like arrays and
and trees stacks

6. Requires more memory Less memory is required


for pointers as no pointers needed

7. Can be used for dynamic Suitable for static data


data structures structures

8. Flexible in terms of size Fixed-size and structure


and structure

9. Random access is not Random access is


possible possible

10. Pointers may be pointing All elements are stored in


to null or non-existent contiguous memory
memory in case of broken
links

11. Can have multiple Only one pointer is


pointers in case of required to traverse the
bidirectional links list
12. Can have a circular linked Only a linear sequential
list list is possible

13. Can have multiple head Only one head and tail
and tail pointers pointer is required

14. Can have variable length Fixed length of data in


of data in each node each element

15. Can be used for Can be used for simple


implementing more data structures like
complex data structures queues and stacks.
like graphs.

Singly Linked List

It is the simplest type of linked list in which every node contains some data
and a pointer to the next node of the same data type.

First node is called the header node where no data element is


stored, but the link field holds the address of the node
containing very first data element.
A single linked list allows the traversal of data only in one way.

Doubly Linked List


A doubly linked list or a two-way linked list is a more complex type of linked list that
contains a pointer to the next as well as the previous node in sequence.

This would enable us to traverse the list in the backward direction as well.
3. Circular Linked List

A circular linked list is that in which the last node contains the pointer to
the first node of the list.

4. Doubly Circular linked list


A Doubly Circular linked list or a circular two-way linked list is a more complex
type of linked list that contains a pointer to the next as well as the previous node
in the sequence.

The difference between the doubly linked and circular doubly list is the same as
that between a singly linked list and a circular linked list.

The circular doubly linked list does not contain null in the previous field of the
first node

Queue: FIRST IN FIRST OUT


Queue is an ordered list (linear data structure) in which insertions(Enqueue) are done at rear
end and deletions(dequeue) are done at the front end of the Queue.
6.2.Applications of Queue Because of the way that line performs activities on first in
first out premise which is very reasonable for the requesting of activities. There are
different uses of queues examined as beneath.

1. Queues are generally utilized as hanging tight records for a solitary shared asset like
printer, plate, CPU.

2. Queues are utilized in offbeat exchange of information (where information isn't being
moved at similar rate between two cycles) for eg. pipes, document IO, attachments.

3. Queues are utilized as cradles in the greater part of the applications like MP3 media
player, CD player, and so on

4. Queue are utilized to keep up the play list in media major parts to add and eliminate
the tunes from the play-list.

5. Queues are utilized in working frameworks for dealing with interferes.

Basic Operations on Queue:


Some of the basic operations for Queue in Data Structure are:

enqueue() – Insertion of elements to the queue.


dequeue() – Removal of elements from the queue.
peek() or front()- returns the data element available at the front node of the queue
without deleting it.
rear() – This operation returns the element at the rear end without removing it.
isFull() – Validates if the queue is full.
isEmpty() – Checks if the queue is empty.

Advantages:

Orderly Processing: Queues follow a first-in, first-out (FIFO) order, ensuring that tasks
or elements are processed in the order they arrive.
Task Scheduling: Queues are useful for managing and scheduling tasks in a systematic
manner, making them suitable for various applications like print spooling, job scheduling, etc.

Buffering: Queues act as buffers in systems, allowing for temporary storage of data or tasks
when the rate of production and consumption varies.

Resource Sharing: Queues facilitate communication and coordination between different


parts of a system or between different processes, enabling efficient resource sharing.

Data Structures: Queues are fundamental data structures used in algorithms and program
design, making them essential for organizing and manipulating data.

Disadvantages of Queues:

Limited Access: Queues typically offer limited access to elements, with operations like
enqueue (adding to the end) and dequeue (removing from the front). Access to elements in
the middle is usually restricted.

Overhead: Implementing and managing queues can introduce overhead in terms of memory
and processing, especially in scenarios with frequent enqueue and dequeue operations.

Complexity: In some scenarios, managing queues can add complexity to the system design,
especially when dealing with priority queues, circular queues, or other variations.

Waiting Time: In systems where tasks are queued up, there can be an inherent waiting time for
tasks to be processed, leading to potential delays in overall system responsiveness.

Potential for Deadlocks: In multi-threaded or distributed systems, the improper use of


queues can lead to issues such as deadlocks, where processes are stuck waiting for each
other to release resources.

circular queue:
A Circular Queue is an extended version of a normal queue where the last element of
the queue is connected to the first element of the queue forming a circle.

The operations are performed based on FIFO (First In First Out) principle. It is also
called ‘Ring Buffer’.
7.3.Uses of Circular Queue

roundabout Queue can be utilized in the accompanying situations: Memory the board:
The roundabout queue gives memory the executives. As we have just seen that in linear
queue, the memory isn't overseen proficiently. Yet, if there should arise an occurrence
of a roundabout queue, the memory is overseen effectively by putting the components
in an area which is unused.

CPU Scheduling: The working framework likewise utilizes the circular queue to embed
the cycles and afterward execute them.

Traffic framework: In a PC control traffic framework, traffic signal is probably the best
illustration of the circular queue. Each light of traffic signal gets ON individually after
each jinterval of time. Like red light gets ON briefly then yellow light briefly and
afterward green light. After green light, the red light gets ON

You might also like