0% found this document useful (0 votes)
13 views18 pages

Selection Sort Algorithm in C: Esha Gupta

136845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views18 pages

Selection Sort Algorithm in C: Esha Gupta

136845
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Selection Sort Algorithm in C

Esha Gupta
Associat e Senior Execut ive
Updated on Sep 3, 2024 13:54 IST
Ever wondered how your favourite music app arranges songs from least to
most played or how an online store lists products from cheapest to priciest?
At the heart of such operations are sorting algorithms – systematic methods
computers use to order data in specific sequences. In this blog, we will
understand about selection sort in c!

Sorting algorithms are fundamental algorithms in computer science designed to


arrange data in a particular order. The order can be numerical (ascending or
descending) or lexicographical. There are several sorting algorithms, each with its
advantages, disadvantages, and use cases. Some of the most commonly studied
sorting algorithms include bubble sort, insertion sort, selection sort, merge sort,
quick sort, heap sort, etc.

Let’s see selection sort algorithm in detail

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
Table of Content
What is Selection Sort

Algorithm of Selection Sort


Basic concept and working principle

Implementation of Selection Sort in C


Complexity Analysis of Selection Sort
Real-world Example of Selection Sort in C

Advantages and Disadvantages

What is Selection Sort


Selection Sort is a simple comparison-based sorting algorithm. Its primary idea is
to divide the input list into two parts: a sorted sublist and an unsorted sublist. Initially,
the sorted sublist is empty, and the unsorted sublist contains all the elements. The
algorithm repeatedly selects the smallest (or largest, depending on the sorting order)
element from the unsorted sublist and moves it to the end of the sorted sublist. This
process continues until the unsorted sublist is empty and the sorted sublist contains
all the elements in the desired order.

Algorithm of Selection Sort


Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Basic concept and working principle

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
Basic concept and working principle
Let’s see the basic working and principles of the selection sort algorithm using your
example array: arr[] = {17, 34, 25, 49, 09}

Selection Sort Working Principle :


Initialization: Start with the f irst element as the current “minimum”
(initially assuming it’s the smallest).
Search f or Minimum: Iterate through the remaining unsorted
elements, comparing each one with the current “minimum.” If you f ind
a smaller element, update the current “minimum.”
Swap: Af ter completing the iteration and f inding the actual minimum
among the unsorted elements, swap it with the f irst unsorted element
(the one you started with).
Repeat: Repeat steps 1-3 f or the next unsorted element, then the
next, until the entire array is sorted.

Here’s how selection sort works step-by-step f or your array

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
Let’s consider this pseudocode snippet
procedure selectionSort(arr: array of integer, n: integer)
declare i, j, minIndex, temp: integer

f or i = 0 to n - 1 do
minIndex = i
f or j = i + 1 to n - 1 do
if arr[j] < arr[minIndex] then
minIndex = j

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
end if
end f or

temp = arr[i]
arr[i] = arr[minIndex]
arr[minIndex] = temp
end f or
end procedure
Now, from the above pseudocode, let’s understand the algorithm step by
step.

Step 0: Consider the Initial Array


arr[] = {17, 34, 25, 49, 09}
The entire array is currently unsorted. The sorted portion is empty.

Step 1: 1st Iteration


Find the smallest element in the entire array and swap it with the first position.

Dry run

Comparison (arr[i] Updated


i j minIndex arr[] Swap?
vs arr[j]) Array
[17, 34,
[17, 34, 25,
0 1 0 17 < 34 No 25, 49,
49, 9]
9]
[17, 34,
[17, 34, 25,
0 2 0 17 < 25 No 25, 49,
49, 9]
9]
[17, 34,
[17, 34, 25,
0 3 0 17 < 49 No 25, 49,
49, 9]
9]

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
[9, 34,
[17, 34, 25,
0 4 4 17 > 9 Yes 25, 49,
49, 9]
17]

arr[] = {09, 34, 25, 49, 17}


The first element, 09 is now in its correct position, and the array is divided into a
sorted portion {09} and an unsorted portion {34, 25, 49, 17}.
Step 2: 2nd Iteration

Find the smallest element in the remaining unsorted portion {34, 25, 49, 17} and
swap it with the second position.

Dry run

Comparison (arr[i] Updated


i j minIndex arr[] Swap?
vs arr[j]) Array
[9, 34,
[9, 34, 25,
1 2 1 34 > 25 No 25, 49,
49, 17]
17]
[9, 34,
[9, 34, 25,
1 3 1 34 < 49 No 25, 49,
49, 17]
17]
[9, 17,
[9, 34, 25,
1 4 4 34 > 17 Yes 25, 49,
49, 17]
34]

arr[] = {09, 17, 25, 49, 34}


Here, sorted portion is {09,17} and unsorted portion is {25,49,34}

Step 3: 3rd Iteration


Find the smallest element in the remaining unsorted portion {25, 49, 34} and swap it

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
with the third position.

Dry run

Comparison (arr[i] Updated


i j minIndex arr[] Swap?
vs arr[j]) Array
[9, 17,
[9, 17, 25,
2 3 2 25 < 49 No 25, 49,
49, 34]
34]
[9, 17,
[9, 17, 25,
2 4 2 25 < 34 No 25, 49,
49, 34]
34]

At the end of this iteration, element 25 is already in its correct position.

arr[] = {09, 17, 25, 49, 34}


Here, sorted portion is {09,17,25} and unsorted portion is {49,34}

Step 4: 4th Iteration


Find the smallest element in the remaining unsorted portion {49, 34} and swap it
with the fourth position.

Dry run

Comparison (arr[i] Updated


i j minIndex arr[] Swap?
vs arr[j]) Array
[9, 17,
[9, 17, 25,
3 4 3 49 > 34 Yes 25, 34,
49, 34]
49]

Now, af ter the 4th iteration, only one element remains 49, which is
inherently in its correct place as it’s the last and largest element in
the list.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
So, at the end of the 4th iteration, the entire array is sorted in
ascending order:
arr[] = {09, 17, 25, 34, 49}
That completes the selection sort for the given array.

Implementation of Selection Sort in C

Step 1: Function Declaration

The selectionSort function is declared to sort a given array.

Step 2: Outer Loop

This loop (f or (i = 0; i < n – 1; i++)) traverses each element of the array,


treating the current element as the boundary between the “sorted” and “unsorted”
portions of the array.

The n-1 concept for the outer loop in the implementation of the Selection Sort
algorithm has to do with the number of passes/iterations required to sort the array
which in this case is 5-1 = 4 iterations (where, n=5)

Step 3: Assume Minimum

Within the outer loop, initially assume that the current element (i-th element) is the
smallest (minIndex = i) .

Step 4: Inner Loop for Minimum Search

The inner loop (f or (j = i + 1; j < n; j++)) searches for the smallest element in
the unsorted portion of the array. If a smaller element is found than the assumed

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
minimum, the minIndex is updated.

Step 5: Swap

After the inner loop completes for each pass of the outer loop, the element at the
minIndex (smallest in the unsorted portion) is swapped with the first element of
the unsorted portion (i-th element).

Step 6: Repeat

The process continues until the outer loop has traversed the entire array, at which
point the array will be sorted.

Step 7: Main Function

The main function initializes the array and its size, then calls the selectionSort
function to sort the array. Before and after the sorting process, the array is printed
to the console for visualization.

Sort ing Algorit hms in Java


So rting is the pro cess o f putting a list, a sequence o f pro vided items, o r data
co llectio n into a specific o rder. In this article, we will discuss different so rting
algo rithms in...re ad m o re

Bucket Sort Algorit hm: Use and Comparison


Bucket so rt refers to a so rting algo rithm that wo rks by distributing elements o f an
array into several buckets. Every bucket is so rted individually, either using a
different so rting algo rithm o r...re ad m o re

Bubble Sort Algorit hm (Wit h Code)


In to day’s wo rld o f co ntinuo us data generatio n, it is o f utmo st impo rtance fo r all
businesses to so rt data linearly and attain relatio nships o n the same. With
different types o f so rting...re ad m o re

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
Code

Copy code

#include < stdio.h>

void selectionSort(int arr[], int n) {


int i, j; // Outer, Inner loop counters
int minIndex; // Smallest element index
int temp; // Swap variable

// Outer loop: up to second-last element


for (i = 0; i < n - 1; i++) {
minIndex = i; // Start with current index

// Inner loop: find smallest in unsorted part


for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // Update smallest index
}
}

// Swap
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}

int main() {
int arr[] = {17, 34 , 25, 4 9, 9}; // Initial array
int n = sizeof(arr) / sizeof(arr[0]); // Array length

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
// Display original array
printf("Original Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

selectionSort(arr, n); // Sort the array

// Display sorted array


printf("Sorted Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

Output
Original Array: 17 34 25 49 9
Sorted Array: 9 17 25 34 49

Complexity Analysis

Time Complexity

1. Best Case

This occurs when the input array is already sorted. Despite the array being sorted,
the Selection Sort algorithm will still go through all its steps trying to find the
smallest element in each iteration because it doesn’t have a mechanism to detect

an already sorted list. Thus, the best-case time complexity is still: O(n2 )

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
2. Average Case

For an average or random list, Selection Sort will have to go through roughly half of
the list for every number. The pattern follows n + (n-1) + (n-2) + … + 2 + 1,

which sums up to n(n+1)/2 . This simplifies to O(n2 ) for large values of n.

3. Worst Case

This happens when the input list is sorted in reverse. However, the behaviour of the
Selection Sort doesn’t change whether it’s a reverse sorted list or any random list. It
still goes through its entire process of finding the smallest element for each

iteration. Hence, the worst-case time complexity is O(n2 )

Space Complexity
Selection Sort is an in-place sorting algorithm, which means it doesn’t require
any additional storage (or “space”) that grows with the input size. It uses a constant
amount of extra space for its variables (i, j, minIndex, temp). Hence, the space
complexity is O(1)

Real-world Example of Selection Sort in C

Scenario
You’re an IT intern at a small e-commerce startup called “QuickShop.” The company
is just getting started, and the website has a feature where sellers can list their
products for sale. Each seller has their own dashboard where they can see all the
products they’ve listed. The startup is very new, and the software is basic. Sellers
have been requesting a feature to sort their products by price so that they can
easily identify and modify their lowest-priced products.

However, the dashboard can display a maximum of 10 products at a time due to


design constraints. As a result, the sorting operation never deals with more than 10

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
items for each seller.

Task
Implement a feature that allows sellers to sort and view their products in ascending
order of price using the Selection Sort algorithm.

Solution
Given the constraints (sorting small lists), Selection Sort can be a reasonable choice
because of its simplicity.

Data Collection: Whenever a seller wants to view their products


sorted by price, retrieve the prices of their listed products (a
maximum of 10).

Sorting Mechanism: Use the Selection Sort algorithm to sort these


prices in ascending order.
Display: Once sorted, display the products on the dashboard in the
sorted order.

Code

Copy code

#include < stdio.h>


#include < string.h>

#define MAX_PRODUCTS 10

typedef struct {
char name[50];
float price;
} Product;

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
// Function to perform Selection Sort based on price
void selectionSort(Product products[], int n) {
int i, j, minIndex;
Product temp;

for (i = 0; i < n-1; i++) {


minIndex = i;
for (j = i+1; j < n; j++) {
if (products[j].price < products[minIndex].price) {
minIndex = j;
}
}
// Swap products[i] and products[minIndex]
temp = products[i];
products[i] = products[minIndex];
products[minIndex] = temp;
}
}

int main() {
Product sellerProducts[MAX_PRODUCTS] = {
{"Shirt", 1999.0},
{"Hat", 14 99.0},
{"Socks", 999.0},
{"Jacket", 24 99.0},
{"Jeans", 2999.0},
{"Watch", 34 99.0},
{"Belt", 4 99.0},
{"Shoes", 1299.0},
{"Sunglasses", 4 999.0},
{"Tie", 3999.0}
};

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
printf("Products before sorting:\n");
for (int i = 0; i < MAX_PRODUCTS; i++) {
printf("%s: %.2f\n", sellerProducts[i].name, sellerProducts[i].price);
}

// Sorting the products by price using Selection Sort


selectionSort(sellerProducts, MAX_PRODUCTS);

printf("\nProducts after sorting by price:\n");


for (int i = 0; i < MAX_PRODUCTS; i++) {
printf("%s: %.2f\n", sellerProducts[i].name, sellerProducts[i].price);
}

return 0;
}

Output
Products bef ore sorting:
Shirt: 1999.00
Hat: 1499.00
Socks: 999.00
Jacket: 2499.00
Jeans: 2999.00
Watch: 3499.00
Belt: 499.00
Shoes: 1299.00
Sunglasses: 4999.00
Tie: 3999.00

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
Products af ter sorting by price:
Belt: 499.00
Socks: 999.00
Shoes: 1299.00
Hat: 1499.00
Shirt: 1999.00
Jacket: 2499.00
Jeans: 2999.00
Watch: 3499.00
Tie: 3999.00
Sunglasses: 4999.00
This code defines a Product structure with a name and price. It then uses the
Selection Sort algorithm to sort an array of these products based on their price. The
main function initializes a list of sample products, displays them, sorts them by
price, and then displays the sorted list.

Advantages and Disadvantages


Based on the above scenario, we can conclude the f ollowing
advantages and disadvantages of our algorithm (Selection Sort)

Aspect Advantage Disadvantage

Would become
Highly ef f icient f or small
inef f icient if QuickShop
Number of datasets like the given
decides to increase the
Items to Sort maximum of 10 items in
number of items
the seller dashboard.
displayed beyond 10.

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
Given the early stage of
As the platf orm grows,
the startup and likely
this simplicity might not
Simplicity limited resources, the
cater to more complex
simplicity of the algorithm
sorting needs.
is a boon.

Can be quickly
Might need to be
implemented without a
replaced with a more
Implementation steep learning curve,
ef f icient sort if the data
Time which is crucial f or a
grows, requiring
startup wanting rapid
redevelopment time.
f eatures.

Doesn’t require additional


memory beyond what’s
No major disadvantages
Memory Usage needed f or the list of
in this context.
items, suiting a lightweight
application.

If sellers were allowed


For small datasets, the
to display more than 10
User sorting will be almost
items, the lag might
Experience instantaneous, ensuring a
become noticeable,
good user experience.
af f ecting UX.

As the company grows,


Maintenance Easy to maintain given its they might need a more
and Scalability simplicity. scalable solution than
selection sort.

Thus, Selection Sort is a straightforward and intuitive sorting algorithm that

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.
operates by repeatedly selecting the smallest (or largest, depending on the order of
sorting) element from an unsorted portion and swapping it with the first unsorted
element. Keep Learning, Keep Exploring!

FAQs

What is Selection Sort?

How does Selection Sort work in C?

Is Selection Sort ef f icient f or large datasets?

Can Selection Sort be used f or sorting strings in C?

What are the advantages of using Selection Sort?

Disclaim e r: This PDF is auto -generated based o n the info rmatio n available o n Shiksha as
o n 0 4-Sep-20 24.

You might also like