You are on page 1of 30

Pearson Higher Nationals in

Computing
Unit 19: Data Structures & Algorithms
Assignment 01
Higher Nationals
Internal verification of assessment decisions – BTEC (RQF)
INTERNAL VERIFICATION – ASSESSMENT DECISIONS
Programme title Higher National Diploma in Computing

Assessor Internal Verifier


Unit 19 – Data Structures and Algorithms
Unit(s)
Specification, Implementation, and Assessment of Data Structures for a
Assignment title sample scenario.

Student’s name
List which assessment criteria Pass Merit Distinction
the Assessor has awarded.

INTERNAL VERIFIER CHECKLIST

Do the assessment criteria awarded match


those shown in the assignment brief?
Y/N
Is the Pass/Merit/Distinction grade awarded
justified by the assessor’s comments on the Y/N
student work?
Has the work been assessed
accurately? Y/N
Is the feedback to the student:
Give details:
• Constructive?
• Linked to relevant assessment criteria?
Y/N
• Identifying opportunities for Y/N
improved performance? Y/N
• Agreeing actions? Y/N
Does the assessment decision need
amending? Y/N

Assessor signature Date

Internal Verifier signature Date


Programme Leader signature (if required)
Date
Confirm action completed
Remedial action taken

Give details:

Assessor signature Date


Internal Verifier
signature Date

Programme Leader
signature (if required) Date

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Higher Nationals - Summative Assignment Feedback Form
Student Name/ID
Unit Title Unit 19: Data Structures and Algorithms

Assignment Number 1 Assessor


Date Received 1st
Submission Date submission
Date Received 2nd
Re-submission Date submission
Assessor Feedback:
LO1 Examine different concrete data structures and it’s valid operations.
Pass, Merit & P1 P2 M1 M2 D1
Distinction
Descripts

LO2 Discuss the advantages, complexity of Abstract Data Type and importance concepts of
Object orientation.

Pass, Merit & P3 M3 D2


Distinction
Descripts

LO3 Implement, Demonstrate and evaluate complex ADT algorithm.

Pass, Merit & P4 P5 M4 D3


Distinction
Descripts

LO4 Examine the advantages of Independent data structures and discuss the need of
asymptotic analysis to assess the effectiveness of an algorithm.
Pass, Merit & P6 P7 M5 D4
Distinction
Descripts

Grade: Assessor Signature: Date:


Resubmission Feedback:

Grade: Assessor Signature: Date:


Internal Verifier’s Comments:
Signature & Date:
* Please note that grade decisions are provisional. They are only confirmed once internal and external moderation has taken place and grades decisions have been
agreed at the assessment board.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Assignment Feedback
Formative Feedback: Assessor to Student

Action Plan

Summative feedback

Feedback: Student to Assessor

Assessor Date
signature

Student signature Date

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
General Guidelines

• A Cover page or title page – You should always attach a title page to your assignment. Use previous
page as your cover sheet and make sure all the details are accurately filled.

• Attach this brief as the first section of your assignment.

• All the assignments should be prepared using a word processing software.

• All the assignments should be printed on A4 sized papers. Use single side printing.

• Allow 1” for top, bottom , right margins and 1.25” for the left margin of each page.

Word Processing Rules

• The font size should be 12 point, and should be in the style of Time New Roman.

• Use 1.5 line spacing. Left justify all paragraphs.

• Ensure that all the headings are consistent in terms of the font size and font style.

• Use footer function in the word processor to insert Your Name, Subject, Assignment No, and
Page Number on each page. This is useful if individual sheets become detached for any reason.

• Use word processing application spell check and grammar check function to help editing your
assignment.

Important Points:

• It is strictly prohibited to use textboxes to add texts in the assignments, except for the compulsory
information. eg: Figures, tables of comparison etc. Adding text boxes in the body except for the before
mentioned compulsory information will result in rejection of your work.

• Carefully check the hand in date and the instructions given in the assignment. Late submissions will
not be accepted.

• Ensure that you give yourself enough time to complete the assignment by the due date.

• Excuses of any nature will not be accepted for failure to hand in the work on time.

• You must take responsibility for managing your own time effectively.

• If you are unable to hand in your assignment on time and have valid reasons such as illness, you may
apply (in writing) for an extension.

• Failure to achieve at least PASS criteria will result in a REFERRAL grade .

• Non-submission of work without valid reasons will lead to an automatic RE FERRAL. You will then
be asked to complete an alternative assignment.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
• If you use other people’s work or ideas in your assignment, reference them properly using HARVARD
referencing system to avoid plagiarism. You have to provide both in-text citation and a reference list.

• If you are proven to be guilty of plagiarism or any academic misconduct, your grade could be reduced
to A REFERRAL or at worst you could be expelled from the course

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Student Declaration

I hereby, declare that I know what plagiarism entails, namely to use another’s work and to present it as my
own without attributing the sources in the correct form. I further understand what it means to copy another’s
work.

• I know that plagiarism is a punishable offence because it constitutes theft.


• I understand the plagiarism and copying policy of Edexcel UK.
• I know what the consequences will be if I plagiarise or copy another’s work in any of the assignments
for this program.
• I declare therefore that all work presented by me for every aspect of my program, will be my own, and
where I have made use of another’s work, I will attribute the source in the correct way.
• I acknowledge that the attachment of this document signed or not, constitutes a binding agreement
between myself and Pearson, UK.
• I understand that my assignment will not be considered as submitted if this document is not attached to
the assignment.

Student’s Signature: Date:


(Provide E-mail ID) (Provide Submission Date)

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Higher National Diploma in Business
Assignment Brief
Student Name /ID Number
Unit Number and Title Unit 19 : Data Structures and Algorithms
Academic Year 2021/22
Unit Tutor
Assignment Title Specification, Implementation, and Assessment of Data Structures for a
sample scenario.
Issue Date
Submission Date
IV Name & Date

Submission format

The submission should be in the form of a report, which contains code snippets (which must be
described well), text-based descriptions, and diagrams where appropriate. References to external
sources of knowledge must be cited (reference list supported by in-text citations) using the Harvard
Referencing style.

Unit Learning Outcomes:

LO1. Examine abstract data types, concrete data structures and algorithms.
LO2. Specify abstract data types and algorithms in a formal notation.
LO3. Implement complex data structures and algorithms.
LO4. Assess the effectiveness of data structures and algorithms.

Assignment Brief and Guidance:

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Scenario
ABC Pvt Ltd organizing Car Racing event across western province and they decided to have
maximum of 6 cars(participants) to compete.
There are totally 3 Rounds and at the end of each round lowest rank car will be eliminated from
the Race.
Each car has unique number, brand, sponsor and driver details.

In order to manage this particular event ABC Pvt Ltd decided to develop an Application.
Application functions are listed down.

1.Register Car Details


2.Delete a car
3.Insert 3 Rounds Results.
4.Find out the winners (1st,2nd,3rd)
5.Search for a particular car

Task 1: Examine and create data structure by simulating the above scenario and explain the
valid operations that can be carried out on this data structure.
Determine the operations of a queue and critically review how it is used to implement function
calls related to the above scenario.

Task 2: Implement the above scenario using the selected data structure and its valid operations
for the design specification given in task 1 by using java programming. Use suitable error
handling and Test the application using suitable test cases and illustrate the system. Provide
evidence of the test cases and the test results.

Task 3 : Registered Car details are stored from oldest to newest. Management of ABC Pvt Ltd
should be able to find from the newest to oldest registered car details. Using an imperative
definition, specify the abstract data type for the above scenario and implement specified ADT
using java programming and briefly discuss the complexity of chosen ADT algorithm. List down
the advantages of Encapsulation and Information hiding when using an ADT selected for the

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
above scenario.
“Imperative ADTs are basis for object orientation.” Discuss the above view stating whether
you agree or not. Justify your answer.

Task 4: ABC Pvt Ltd plans to visit all of these participants through the shortest path within a
day.
Analyse the above operation by using illustrations, of two shortest path algorithms, specify how
it operates using a sample graph diagram. Sort the cars based on numbers with two different
sorting algorithms and critically review the performances of those two algorithms by comparing
them.

Task 5: Evaluate how Asymptotic analysis can be used to assess the effectiveness of an
algorithm and critically evaluate the different ways in which the efficiency of an algorithm can
be measured.
Critically review the sort of trade-offs exists when you use an ADT for implementing programs.
You also need to evaluate the benefits of using independent data structures for implementing
programs.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Grading Rubric

Grading Criteria Achieved Feedback

LO1. Examine abstract data types,


concrete data structures and algorithms.

P1 Create a design specification for data


structures explaining the valid operations that
can be carried out on the structures.

P2 Determine the operations of a memory


stack and how it is used to implement
function calls in a computer.

M1 Illustrate, with an example, a concrete


data structure for a First In First out (FIFO)
queue.

M2 Compare the performance of two sorting


algorithms.
D1 Analyse the operation, using illustrations,
of two network shortest path algorithms,
providing an example of each.

LO2. Specify abstract data types and


algorithms in a formal notation.

P3 Using an imperative definition, specify the


abstract data type for a software stack.

M3 Examine the advantages of encapsulation and


information hiding when using an ADT.

D2 Discuss the view that imperative ADTs

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
are a basis for object orientation and, with
justification, state whether you agree.

LO3. Implement complex data structures


and algorithms.

P4 Implement a complex ADT and algorithm


in an executable programming language to
solve a well-defined problem.
P5 Implement error handling and report test
results.
M4 Demonstrate how the implementation of
an ADT/algorithm solves a well-defined
problem.
D3 Critically evaluate the complexity of an
implemented ADT/algorithm.
LO4. Assess the effectiveness of data
structures and algorithms.
P6 Discuss how asymptotic analysis can be
used to assess the effectiveness of an
algorithm.
P7 Determine two ways in which the efficiency of
an algorithm can be measured, illustrating your
answer with an example.

M5 Interpret what a trade-off is when


specifying an ADT using an example to
support your answer.
D4 Evaluate three benefits of using
implementation independent data structures.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
S. P. F Raisha Unit 19: Data Structures and Algorithms
[Type here]
Task 01
1.1 Data structures and Algorithms

A data structure is a way to organize data in a virtual system. Consider number sequences or data tables:
both are well-defined data structures. An algorithm is a set of steps performed by a computer to change
an input into a desired output. Data structures and algorithms work together to allow programmers to
create any computer programs they want. A thorough understanding of data structures and algorithms
ensures that code is well-optimized and efficient (Gupta, 2020).

1.2 Common Data Structures and Algorithms

1.2.1 Stack
A stack is a LIFO (Last in First Out the element placed at last can be accessed at first) structure which can
be commonly found in many programming languages. This structure is named as “stack” because it
resembles a real-world stack, a stack of plates (Mallawaarachchi, 2020).

Operations on the stack


The two fundamental operations that may be done on a stack are listed below (Mallawaarachchi, 2020).

ˉ Push: Add a new element to the top of the stack.


ˉ Pop: Delete and return the topmost element.

Figure 01: Visualization of basic Operations of Stacks

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
PUSH Operation Algorithm of Stack

#Pseudo code

if TOP = MAX-1

return "Overflow"

endif

top = top + 1

stack[top] = item

end

Table: PUSH Operation Algorithm of Stack

Code Snippet of PUSH Operation

public void push(int x)


    {
        if (top >= (MAX - 1)) {
            System.out.println("Stack Overflow");
        }
        else {
            a[++top] = x;
            System.out.println("Item pushed into stack = "+x);
        }
    }

Table: Code Snippet of PUSH Operation

POP Operation Algorithm of Stack

#Pseudo code

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
If TOP=-1

return "Underflow"

endif

item=Stack[Top]

top=top-1

return Item

end

Table: POP Operation Algorithm of Stack

Code Snippet of POP Operation

public int pop()


    {
        if (top < 0) {
            System.out.println("Stack Underflow");
            return 0;
        }
        else {
            int x = a[top--];
            return x;
        }
    }

Table: Code Snippet of POP Operation

Applications of stacks

ˉ Used to evaluate expressions (e.g.: shunting-yard algorithm for parsing and evaluating
mathematical expressions).
ˉ In recursion programming, this is used to generate function calls.

1.2.2 Queue

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
A queue is a First In First Out (FIFO) structure, which is frequently used in various programming
languages and refers to the idea that the element inserted first may be retrieved first. Because it resembles a
real-world queue, a queue of people waiting, this structure is called a "queue" (Mallawaarachchi, 2020).

Queue operations
The two fundamental operations that may be carried out on a queue are listed below.

ˉ Enqueue: Add an element to the queue's end.


ˉ Dequeue: Remove the element from the queue's top.

Figure 02: Visualization of Basic Operations of Queues

Algorithm to insert any element in a queue


Algorithm
#Pseudo code
Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Step 3: Set QUEUE[REAR] = NUM
Step 4: EXIT

Table: Pseudo code of queue


Code of C insert function

Figure: Code for C insert function

Applications of queues

ˉ Thread management in multithreading.


ˉ Used in the implementation of queuing systems (e.g: priority queues).

1.2.3 linked lists

A linked list is a sequential structure composed of a series of elements in linear order that are linked to one
another. As a result, you must access data sequentially; random access is not feasible. Linked lists are a
straightforward and adaptable way to express dynamic sets (Mallawaarachchi, 2020).

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Consider the following words in relation to linked lists.
ˉ Nodes are the elements of a linked list.
ˉ Each node has a key and a reference to the node that comes after it, known as next.
ˉ The head property corresponds to the first member of the linked list.
ˉ The tail is the final member of the linked list.

Figure 03: Visualization of basic Terminology of Linked Lists

Types of Linked list

- Singly-linked list - A singly-linked list is a collection of an ordered set of entries. A node in a


single linked list is made up of two parts: the data component and the link part. The data element of
the node holds the actual information that the node will represent, while the link part of the node
maintains the address of its immediate successor (Javatpoint, n.d.).

- Doubly linked list - A doubly linked list is a sort of linked list that carries a reference to both the
previous and next node in the sequence. A node in a doubly-linked list therefore consists of three
parts: node data, a reference to the next node in sequence (next pointer), and a pointer to the
previous node (previous pointer) (previous pointer) (Javatpoint, n.d.).

- Circular singly linked list - The final node of a circular singly linked list carries a reference to the
beginning node of the list. There are circular singly linked lists and circular doubly linked lists
(Javatpoint, n.d.).

- Circular doubly linked list - A circular doubly linked list is a more complicated data structure in
which each node has references to the node before it as well as the node after it. There are no
NULL nodes in the circular doubly linked list. The address of the first node in the list is contained
in the list's final node. In its previous pointer, the first node in the list also carries the address of the
last node (Javatpoint, n.d.).

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Linked List Operations

ˉ Search: Using a basic linear search, find the first element with the key k in the supplied linked list and
return a reference to this element.
ˉ Insert: Insert a key into the linked list. Insertion can be performed in three ways: at the start of the list,
at the end of the list, or in the middle of the list.
ˉ Delete: Removes element x from a linked list. A node cannot be deleted in a single step. A deletion
can be performed in three ways: from the beginning of the list, from the end of the list, or from the
middle of the list.

Algorithm of Insertion in singly linked list at beginning

Figure: Step 1: IF PTR = NULL Algorithm of linked list


Write OVERFLOW
Go to Step 7
C [END OF IF] Function

Step 2: SET NEW_NODE = PTR


Step 3: SET PTR = PTR → NEXT
Step 4: SET NEW_NODE → DATA = VAL
Step 5: SET NEW_NODE → NEXT = HEAD
Step 6: SET HEAD = NEW_NODE
Step 7: EXIT

#include<stdio.h>  
#include<stdlib.h>  
void beginsert(int);  
struct node  
{  
    int data;  
    struct node *next;  

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
};  
struct node *head;  
void main ()  
{  
    int choice,item;  
    do   
    {  
        printf("\nEnter the item which you want to insert?\n");  
        scanf("%d",&item);  
        beginsert(item);  
        printf("\nPress 0 to insert more ?\n");  
        scanf("%d",&choice);  
    }while(choice == 0);  
}  
void beginsert(int item)  
    {  
        struct node *ptr = (struct node *)malloc(sizeof(struct node *));  
        if(ptr == NULL)  
        {  
            printf("\nOVERFLOW\n");  
        }  
        else  
        {  
            ptr->data = item;  
            ptr->next = head;  
            head = ptr;  
            printf("\nNode inserted\n");  
        }  
          
    }  

Table: C function of Linked list

Applications of linked lists


ˉ In compiler design, it is used to handle symbol tables.
ˉ When switching between programs, Alt + Tab is used (implemented using Circular Linked List).

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
1.3 Suitable data Structure for given scenario

The linked list is suitable for this scenario because it works in the same way as all of the system functions
listed below; Main functions:

1) Add Car details

2) Delete a car

3) Insert 3 rounds results

4) Find out the winners

5) Search a particular

ABC (PVT) LTD is organizing an automotive event for 6 people and they decide to create an app for it.

In this basic application method, the first thing required to register an auto part is called sequentially. It
can also be used as a queue, nor can it be used as a queue as other functions cannot use the ones specified
here.

If we use a Linked List we can do this however we want. By entering the vehicle data, we can enter more
than one vehicle data at the same time. As an example, please enter the controller network card number
as a string, but we need to enter its age as a whole number.

We need to enter different kinds of details at the same time, then I suggested a possible function: Linked
List.

The next feature is the app's Lift Car feature. For this we can use three stacks, queues and Linked List for
our needs. Using the stack function we can remove only the last item from the given list. This is because
this is a first-in, last-out, or last-in, first-out theory, and the order cannot be used because the general
theory is first-in, first-out. This means we can delete the initial data from the list. So we can use Linked
List function to do this, then we can easily control what we want to do.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Add 3 round results for the next function. We can use the last-in, first-out method of the stack functions,
but the same can be done using the Linked List function here.

The next step is that we want to find the winners and the position as 1, 2 and 3. As mentioned above,
three functions can be used for this, but Linked List is the most convenient function because other
functions cannot do what is required here.

The last function will be Find custom car from the list. We can't use the other 2 builds here because
neither of these 2 builds can do what is required. So the most suitable structure for this is the linked list.
Therefore, it is better to choose the linked list for the next function.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Task 02

2.1 Car racing system for ABC PVT Ltd


Below shows what system created for ABC private limited. hope to show you the code for the key
components that should be in the system and the test cases to test them. Here showing the codes and
some of the main features that will apply to the system.

1) Car registration data

2) Deleting a Car

3) Search a Car

4) Adding the results of 3 rounds and determining the winners (1st, 2nd, 3rd) Codes and Test Case for
Register Car Details

Here are some methods and basic functions in the system for this section and if it is not possible to create
this section correctly it will cancel the proposed system. Because the data we get from this section refers
to the last section of the system. "Identification of winners (1, 2, 3)". Accordingly, if we don't properly
create this segment here, ultimately all the data we get from this system is doomed to be out of core. For
this reason, I have tried to make this section meticulously down to the smallest detail. Below have used
two main strategies for this segment. where necessary and would like to independently clarify what is
going on with them. Methods used
ˉ Add method

ˉ Add to list method

2.1.1 Add Method


This is done by validating the data provided by the client and sending each information to the Add to list
method. Similarly, will get all the data about id, make, sponsor, driver name, driver age and registration
date of the currently registered vehicle and then export it to the Add to list method.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Test Case for Add Car details

Test Feature Add a car


Testing Car Details Add
Inputs Car Id = CR23
Brand = Honda
Sponsor = ABC PVT LTD
Driver’s First Name = Dilantha
Driver’s Last Name= Malagamuva
Driver’s Age = 30
Expected outcome Successfully add Car Details You Added Details are:
[CR23, Honda, ABC PVT LTD, Dilantha,
Malagamuva,30]
Actual Outcome Successfully add Car Details You Added Details are:
[CR23, Honda, ABC PVT LTD , Dilantha,
Malagamuva,30]
Test successful Yes/No Yes

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
Task 03

3.1 Introduction to Sorting


It is a method of arranging the components in a list in a specific order, either ascending or descending.
Efficient sorting is critical for optimizing the usage of other algorithms that require a sorted list to
function properly, such as search and merge (Sonal, 2020).

3.1.1 Types of Sorting Insertion sort

3.1.1.1 Bubble sort


Bubble sort is a straightforward but inefficient sorting method. It is often one of the fundamental
algorithms taught in programming classes to help students get a strong understanding for how algorithms
function.

Bubble sort steps


Can execute two nested loops Algorithm:

I. Attempt to place one input value in the right location in the sorted output at each level of the outer
loop. So, from I -- 0 to n-1, repeat the outer loop n times.
After the first k iterations I -- 0 to k-1) of the outer loop, all k maximal items have been moved from
one index (n -- k) to a new index (n -- k) (n-1). So, during the (k + 1)th iteration of the outer loop
(where I -- k), the (k + 1)th maximum element must be placed at the (n -- k -1)th index. So an inner
loop from n -- k -- 1 or n -- I -- 1 must be executed. In other words, the inner loop will run from j --
0 through n -- I -- 2.

for(int i = 0; i < n; i = i + 1)
{
for(int j = 0; j < n - i - 1; j = j + 1)
{
........
}
}

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
II. The crucial question now is: What is the reasoning inside the inner loop? The concept would be
straightforward: Starting with the first index, compare adjacent pairs of items from left (j= 0) to
right (j -- n – I -- 2), swapping their locations if they appear in the improper sequence. Larger
components "bubble up" to the correct index n -- I -- 1.

for(int j = 0; j < n - i - 1; j = j + 1)
{
if(X[j] > X[j+1])
{
temp = A[j]
X[j] = X[j+1]
X[j+1] = temp
}
}

Bubble Sort Pseudocode

void bubbleSort(int X[], int n)


{
int temp
for(int i = 0; i < n; i = i + 1)
{
for(int j = 0; j < n - i - 1; j = j + 1)
{
if( X[j] > X[j+1])
{
temp = A[j]

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
X[j] = X[j+1]
X[j+1] = temp
}
}
}
}

3.1.1.2 Selection Sort Algorithm


The principle behind this approach is straightforward: search the whole array for the smallest element.
Once it's found, exchange the smallest element with the array's first element. Then, in the remaining array
(minus the first member), find the smallest element and swap it with the second element. This method is
repeated until the entire array is sorted. In general, it maintains two subarrays in a given array at each it
step of the process.
1) The previously sorted subarray X[0...i-1]
2) The last subarray X[i...n-1] is unsorted.

Progressively construct the partial solution or sorted array by finding the minimum value from the
unsorted component and adding it to the sorted section. Our sorted part size will increase by one at each
iteration, while the unsorted part size will drop by one.

Selection Sort Steps


Two nested loops are required: an outer loop to sort all n elements and an inner loop to locate the smallest
element in the remaining array for each iteration of the outer loop.

1) Run the outer loop from I = 0 to n-2 and continue the steps below until the array is sorted.
Initialize the variable Also min Index to hold the unsorted part's minimal value index.

2) Run an inner loop from j = I to n-1 for each index I to get the index of the lowest value in the
unsorted portion.

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]
int min_Index = i
for (int j = i; j < n; j = j + 1)
{
if (X[j] > X[min_Index])
min_Index = j
}

3) Now, swap the value at i with the value at min Index to get the minimal value at ith index, i.e.
swap (X[min index], X[i]).

Selection Sort Pseudocode

selectionSort(int X[], int n)


{
int min_index
for (int i = 0; i < n - 1; i = i + 1)
{
min_index = i
for (int j = i; j < n; j = j + 1)
{
if (X[j] < X[min_index])
min_index = j
}
swap(X[min_index], X[i])
}
}

3.1.1.3 Insertion Sort Algorithm

S. P. F Raisha Unit 19: Data Structures and Algorithms


[Type here]

You might also like