03 DS Sorting
03 DS Sorting
Sorting
Sorting is the process of arranging a set of data in certain order.
Internal Sorting
Deals with sorting the data held in memory of the computer
External Sorting
Deals with sorting the data stored in data files, it is used when
volume of data is very large and cannot be held in computers main
memory
Process Flow:
Read array size.
Read an array of values.
Sort the given array.
Print sorted values.
04/24/2025 3
Selection Sort
Finding smallest in each iteration
Begin
set small = a[k-1]
set loc = k-1
for j = k to (n-1) by 1 do
if (a[j]< small) then
set small = a[j]
set loc = j
end if
end for
End
04/24/2025 4
Void SelectionSort(int a[], int n)
{
int temp, small, loc, I, j;
For (i=1;i<=(n-1);i++)
{
small = a[i-1];
Selection Sort
Loc=i-1;
For (j=1;j<=(n-1);j++)
{
If(a[j]<small)
{ Analysis
Small=a[j];
Loc=j; F(n) = (n-1) +(n-2) +………+/3 +2+1
} = n (n-1 ) / 2
= O (n2 )
}
If(loc !=(i-1) {
temp=a[i-1];
a[i-1]=a[loc];
a[loc]= temp;
}
} 04/24/2025 5
Bubble Sort
Bubble sort is a simple and well-known
sorting algorithm.
Bubble sort belongs to O(n2) sorting
algorithms, which makes it quite inefficient
for sorting large data volumes.
Bubble sort is stable and adaptive.
Algorithm
04/24/2025 6
Bubble Sort
04/24/2025 7
Bubble Sort
Begin
for k = 1 to (n-1) by 1 do
for j = 0 to (n-k-1) by 1 do
If ( a[j] > a[j+1] ) then
set temp = =a [j]
set= a[j] = a [j+1]
a[j+1]= temp
End if
End for Analysis
End for
F(n) = (n-1) +(n-2) +………+/3 +2+1
End = n (n-1 ) / 2
= O (n )2
04/24/2025 8
Insertion Sort
Insertion sort belongs to the O(n2) sorting algorithms.
Unlike many sorting algorithms with quadratic complexity,
it is actually applied in practice for sorting small arrays of
data.
For instance, it is used to improve quicksort routine.
Algorithm
Insertion sort algorithm somewhat resembles selection sort.
unsorted one.
At the beginning, sorted part contains first element of the
04/24/2025 9
Insertion Sort
04/24/2025 10
Insertion Sort
04/24/2025 11
Analysis [no of comparisons ]
04/24/2025 12