mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-14 19:00:15 +08:00
formatting source-code for 153fb7b8a5
This commit is contained in:
@@ -6,14 +6,12 @@
|
||||
|
||||
// Function returns the minimum number of swaps
|
||||
// required to sort the array
|
||||
int minSwaps(int arr[], int n)
|
||||
{
|
||||
int minSwaps(int arr[], int n) {
|
||||
// Create an array of pairs where first
|
||||
// element is array element and second element
|
||||
// is position of first element
|
||||
std::pair<int, int> *arrPos = new std::pair<int, int>[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
for (int i = 0; i < n; i++) {
|
||||
arrPos[i].first = arr[i];
|
||||
arrPos[i].second = i;
|
||||
}
|
||||
@@ -31,8 +29,7 @@ int minSwaps(int arr[], int n)
|
||||
int ans = 0;
|
||||
|
||||
// Traverse array elements
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
for (int i = 0; i < n; i++) {
|
||||
// already swapped and corrected or
|
||||
// already present at correct pos
|
||||
if (vis[i] || arrPos[i].second == i)
|
||||
@@ -42,8 +39,7 @@ int minSwaps(int arr[], int n)
|
||||
// this cycle and add in ans
|
||||
int cycle_size = 0;
|
||||
int j = i;
|
||||
while (!vis[j])
|
||||
{
|
||||
while (!vis[j]) {
|
||||
vis[j] = 1;
|
||||
|
||||
// move to next node
|
||||
@@ -52,8 +48,7 @@ int minSwaps(int arr[], int n)
|
||||
}
|
||||
|
||||
// Update answer by adding current cycle.
|
||||
if (cycle_size > 0)
|
||||
{
|
||||
if (cycle_size > 0) {
|
||||
ans += (cycle_size - 1);
|
||||
}
|
||||
}
|
||||
@@ -65,8 +60,7 @@ int minSwaps(int arr[], int n)
|
||||
}
|
||||
|
||||
// program to test
|
||||
int main()
|
||||
{
|
||||
int main() {
|
||||
int arr[] = {6, 7, 8, 1, 2, 3, 9, 12};
|
||||
int n = (sizeof(arr) / sizeof(int));
|
||||
std::cout << minSwaps(arr, n);
|
||||
|
||||
Reference in New Issue
Block a user