DSA - Lab3 Sorting Techniques1
DSA - Lab3 Sorting Techniques1
Lab Manual 03
CS201: Data Structure and Algorithms
Class: BSCS-2k22
Lab 3: Sorting techniques-I
Instructors:
Mr. Awais Mehmood
[email protected]
&
Mr. M. Faheem Saleem
[email protected]
Lab Manual 3
Introduction
This lab is about the sorting Operations on Arrays in C++.
Objectives
The objectives of this session is to understand the various sorting operations on arrays in C++.
Tools/Software Requirement
Dev C++
Goals for today’s lab:
Sorting Arrays:-
The process of arranging data in a specified order is called sorting. Numeric type data may be
arranged either in ascending or in descending order. Similarly character type data may be
arranged in alphabetical order.
There are different methods to sort data into a list. The most commonly used methods are:
1. Bubble Sort
2. Selection Sort
Bubble Sort:-
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be
sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order.
First pass bubble out the largest element and places in the last position and second pass place the
second largest in the second last position and so on. Thus, in the last pass smallest items is placed
in the first position. Because, it only uses comparisons to operate on elements, it is a comparison
sort.
Example:-
Let us take the array of numbers "5 1 4 2 9", and sort the array from lowest number to greatest
number using bubble sort algorithm. In each step, elements written in bold are being compared.
( 5 1 4 2 9 ) ⟶ ( 1 5 4 2 9 ), Here, algorithm compares the first two elements, and swaps them.
( 1 4 2 5 9 ) ⟶ ( 1 4 2 5 9 ), Now, since these elements are already in order (9 > 5), algorithm
(14259)⟶(14259)
(12459)⟶(12459)
( 1 2 4 5 9 ) ⟶ ( 1 2 4 5 9)
(12459)⟶(12459)
(12459)⟶(12459)
Example 4:-
{6, 1, 2, 3, 4, 5}
Algorithm:-
1. Start with the first element as the minimum element in the unsorted part.
2. Iterate through the unsorted part to find the actual minimum element.
a. Initialize a variable `minIdx` to the index of the current element.
b. For each element in the unsorted part:
- If the current element is less than the element at `minIdx`, update `minIdx` to
the index of the current element.
3. Swap the minimum element (found at `minIdx`) with the first element in the unsorted
part.
4. Move the boundary between the sorted and unsorted parts one element to the right by
incrementing the index where the sorted part ends.
5. Repeat steps 1-4 until the entire array is sorted.
#include <iostream>
using namespace std;
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
return 0;
}