These observations hold, no matter what the input data is.
In the worst case, this could be quadratic, but in the
average case, this quantity is
O(n log n)
. It implies that
the
running time of Selection sort is quite insensitive
to the input
.

Selection Sort
Suppose the name of the array is A and it
has four elements with the following values:
4
19
1
3
To sort this array in ascending order,
n-1, i.e. three iterations will be
required.

Selection Sort
Iteration-1
The array is scanned starting from the first to the last
element and the element that has the smallest value is
selected. The smallest value is 1 at location 3. The address
of element that has the smallest value is noted and the
selected value is interchanged with the first element
i.e.
A[1] and A[3] are swapped
4
19
1
3
1
19
4
3

Selection Sort
Iteration-2
The array is scanned starting from the second to the last
element and the element that has the smallest value is
selected. The smallest value is 3 at location 4. The address
of element that has the smallest value is noted. The
selected value is interchanged with the second element
i.e.
A[2] and A[4] are swapped
1
19
4
3
1
3
4
19

Selection Sort
Iteration-3
The array is scanned starting from the third to the last
element and the element that has the smallest value is
selected. The smallest value is 4 at location 3. The address
of element that has the smallest value is noted. The
selected value is interchanged with the third element
i.e.
A[3] and A[3] are swapped
1
3
4
19
1
3
4
19

Selection Sort – Pseudocode
Input:
An array
A
[1..
n
] of
n
elements.
Output:
A
[1
..n
] sorted in descending order
1. for
i
1 to
n -
1
2.
min
i
3.
for
j
i
+ 1 to
n
{Find the
i th
smallest element.}
4.
if
A
[
j
]
< A
[
min
] then
5. min
j
6.
end for
7.
if min
i
then interchange
A
[
i
] and
A
[min]
8. end for

Program

Output
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
cout<<"\nSorted list is as
follows\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
return 0; }

Assignment
Exercise 3.1 – Solve at least 8 problems out
of 14. If someone will solve all the problems,
then she will get bonus marks

#### You've reached the end of your free preview.

Want to read all 30 pages?

- Fall '19