Uploaded by furquan108549

DSA LAB 3

advertisement
DATA STRUCTURES AND
ALGORITHM
(CSL 221)
LAB MANUAL
DEPARTMENT OF COMPUTER ENGINEERING
BAHRIA UNIVERSITY
ISLAMABAD CAMPUS
Data Structures and Algorithm, Spring 2022
1
LAB NO. 3
Introduction to Sorting Techniques I:
(SELECTION Sort, INSERTION Sort, BUBBLE Sort)
OBJECTIVE:
To understand the concept of Selection Sort, Bubble Sort and Insertion Sort.
DESCRIPTION:
Sorting
Sorting is a process that organizes a collection of data into either ascending or descending order.
There are many sorting algorithms, such as:
Selection Sort
Insertion Sort
Bubble Sort
Merge Sort
Quick Sort
Heap Sort
Radix Sort
The first three are the foundations for faster and more efficient algorithms.
SELECTION Sort:The list is divided into two sublists, sorted and unsorted, which are divided by an imaginary wall.
At the beginning, sorted part is empty, while unsorted one contains whole array.
At every step, algorithm finds the smallest element from the unsorted sublist and swap it with the
element at the beginning of the unsorted data.
After each selection and swapping, the imaginary wall between the two sublists move one element
ahead, increasing the number of sorted elements and decreasing the number of unsorted ones.
Each time we move one element from the unsorted sublist to the sorted sublist, we say that we have
completed a sort pass.
A list of n elements requires n-1 passes to completely rearrange the data.
When unsorted part becomes empty, algorithm stops.
Data Structures and Algorithm, Spring 2022
2
INSERTION Sort:Array is imaginary divided into two parts:
Sorted
Unsorted
At the beginning, sorted part contains first element of the array and unsorted one contains the rest.
At every step, algorithm takes first element in the unsorted part and inserts it to the right place of
the sorted one. When unsorted part becomes empty, algorithm stops. A list of n elements will take
at most n-1 passes to sort the data.
Data Structures and Algorithm, Spring 2022
3
BUBBLE Sort:▪
▪
▪
▪
Compare each pair of adjacent elements from the beginning of an array and, if they
are in reversed order, swap them.
If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At
the step, when no bubble moves, sorting stops.
Given a list of n elements, bubble sort requires up to n-1 passes to sort the data.
LAB TASK:
1. Write a program that sort the numbers in ascending order using the following
techniques:
● Selection Sort
● Insertion Sort
● Bubble Sort:
The output of the program should be like:
Data Structures and Algorithm, Spring 2022
4
2. Write a program to sort given array in descending order using selection sort
technique. Use recursion to perform this.
6 5 7 2 1
.
DELIVERABLES:
1. Task1.cpp
2. Task2.cpp
Data Structures and Algorithm, Spring 2022
5
Download