Lab02 Array Sorting
Lab02 Array Sorting
02
Objectives:
To implement Sorting algorithms (Insertion Sort, Selection Sort) on Contigous Data Structures.
Introduction
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Most common orders are in numerical or lexicographical
order.
The importance of sorting lies in the fact that data searching can be optimized to a very high
level, if data is stored in a sorted manner. Sorting is also used to represent data in more
readable formats. Following are some of the examples of sorting in real-life scenarios −
Telephone Directory − The telephone directory stores the telephone numbers of people sorted
by their names, so that the names can be searched easily.
Dictionary − The dictionary stores words in an alphabetical order so that searching of any word
becomes easy.
When we can adjust the data to be sorted in the main memory itself without any need of
another auxiliary memory, then we call it as Internal Sorting.
On the other hand, when we need auxiliary memory for storing intermediate data during
sorting, then we call the technique as External Sorting.
In this Lab, we will learn the two basic sorting techniques in C++.
Insertion Sort
Selection Sort
Insertion Sort:
Algorithm
Here are the simple steps by which we can achieve insertion sort.
Pseudocode
procedure insertionSort( A : array of items )
int holePosition
int valueToInsert
end for
end procedure
Selection Sort
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-
based algorithm in which the list is divided into two parts, the sorted part at the left end and
the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is
the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues moving
unsorted array boundary by one element to the right.
Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Pseudocode
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
end procedure
EXERCISE
1. Develop the code using the provided insertion-sort algorithm and Selection Sort Algorithm
for sorting an array and print the output.
Code:
Output: