Algo Assignment-03 Selection Sort
Algo Assignment-03 Selection Sort
GROUP-B
(Sorting: Quadratic & logarithmic time complexities)
Assign- 1) Implement Selection Sort (The program should report the number of
pass & comparisons)
PROCEDURE
In selection sort, the smallest value among the unsorted elements of the array is
selected in every pass and inserted to its appropriate position into the array. It is also
the simplest algorithm. It is an in-place comparison sorting algorithm. In this
algorithm, the array is divided into two parts, first is sorted part, and another one is
the unsorted part. Initially, the sorted part of the array is empty, and unsorted part is
the given array. Sorted part is placed at the left, while the unsorted part is placed at
the right.
In selection sort, the first smallest element is selected from the unsorted array and
placed at the first position. After that second smallest element is selected and placed
in the second position. The process continues until the array is entirely sorted.
The average and worst-case complexity of selection sort is O(n2), where n is the
number of items. Due to this, it is not suitable for large data sets.
ALGORITHM
SELECTION SORT(ARR, N)
Step 1: Repeat Steps 2 and 3 for K = 1 to N-1
Step 2: CALL SMALLEST(ARR, K, N, POS)
Step 3: SWAP A[K] with ARR[POS]
[END OF LOOP]
Step 4: EXIT
/* Selection Sort */
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
int Smallest(int[],int,int);
int com=0, tcom=0;
void main()
{
clrscr();
FILE *in;
int n, i, Item, a[100];
cout<<"Enter Sample Size (No of Elements):";
cin>>n;
in=fopen("Algo\\Input.txt", "r");
i=0;
while(!feof(in))
fscanf(in, "%d", &a[i++]);
fclose(in);
FILE *out;
out=fopen("Algo\\Output.txt", "a+");
for(i=0;i<n;i++)
{
int pos = Smallest(a,n,i);
int temp = a[i];
a[i]=a[pos];
a[pos] = temp;
fprintf(out, "Pass:%d Comarison:%d", i+1, com);
tcom+=com;
}
getch();
}
OUTPUT
Do yourself
DISCUSSION
Now, for the first position in the sorted array, the entire array is to be scanned
sequentially.
At present, 12 is stored at the first position, after searching the entire array, it
is found that 8 is the smallest value.
So, swap 12 with 8. After the first iteration, 8 will appear at the first position in
the sorted array.
The same process is applied to the rest of the array elements. Now, we are
showing a pictorial representation of the entire sorting process.
Time Complexity
Case Time Complexity
Best Case: O(n2)
Average Case: O(n2)
Worst Case: O(n2)
Best Case Complexity - It occurs when there is no sorting required, i.e. the
array is already sorted. Then best-case time complexity sort is O(n2).
Literature Review