Minimum Swaps Required to Sort an Array

preview_player
Показать описание
An efficient algorithm to find the minimum number of swaps required to sort the array in ascending order.

Problem:
We have an unordered array consisting of consecutive distinct integers ∈ [1,2,3,...n], where n is the size of the array.
We are allowed to swap any two elements.
We need to find the minimum number of swaps required to sort the array in ascending order.

Algorithm Concept:
1. Look at each index and compare the index position with its element value if its same then move to the next index position.
2. If index position is not the same as element value then treat element value as index value for finding the next element.
3. If we come back to the visited element then there exist a cycle, then count the size of that cycle, the number of swaps for particular cycle would be size-1, do this for all the cycles and add them together.

Outline (check the comment section for a clickable version):
00:00 : Introduction
00:06 : Problem
00:52 : Wrong Approach (Brute Force) Method with Animation Example
01:31 : Algorithm Concept
02:23 : Efficient Solution with Animation Example
05:44 : Code Implementation of Algorithm

Code Available At:
Рекомендации по теме
Комментарии
Автор

Really very effective approach to reduce swap counts.the way of explaining is very good and understandable. Thankyou so much.

vikashpanchal
Автор

Great!! You have Explained well and implemented optimal solution

anandsehgal
Автор

I understand the logic
can someone explain why this works?

rengaisok
Автор

this will only work for non duplicate values.
nevertheless good work

abhinavghosh
Автор

Thanxx.. I really enjoyed the way you explained the concept.

kratikamaheshwari
Автор

Very good explanation. Looking forward to more videos.

ruchirsrivastava
Автор

Awesome. Very nicely and clearly explained !!

AnkitSingh-gizw
Автор

gr8 video!! make more videos for common problems

akshatgupta
Автор

The explanation is AWESOME but the code is broken. could you please check it

Anubis
Автор

We can use selection sort which always takes least no. of swappings to sort an array.
In the given array selection sort will take 1 swapping only.

AnkitSharma-hkyq