05 - DS - Sorting-1
05 - DS - Sorting-1
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.
11/12/2024 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
11/12/2024 4
Void SelectionSort(int a[], int n) Selection Sort
{
int temp, small, loc, I, j;
For (i=1;i<=(n-1);i++)
{
small = a[i-1];
Loc=i-1;
For (j=i; j<=(n-1);j++)
{
If(a[j]<small)
{
Small=a[j];
Loc=j;
}
}
If(loc !=(i-1) {
Analysis
temp=a[i-1];
a[i-1]=a[loc];
F(n) = (n-1) +(n-2) +………+/3 +2+1
a[loc]= temp;
= n (n-1 ) / 2
} = O (n2 )
} 11/12/2024 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
11/12/2024 6
Bubble Sort
11/12/2024 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
temp = a [j]
a[j] = a
[j+1]
a[j+1]= temp
End if
End for
End for
End
Analysis
Algorithm
Insertion sort algorithm resembles selection sort.
11/12/2024 9
Insertion Sort
11/12/2024 10
Insertion Sort
11/12/2024 11
Analysis [no of comparisons ]
11/12/2024 12