Respuesta :

Answer:

// C++ program for implementation of selection sort

#include <bits/stdc++.h>

using namespace std;

// function to perform selection sort

void selectionSort(int a[], int n)

{

   // variables

int i, j, m_idx;

int t;

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

{

    // find the smallest element

 m_idx = i;

 for (j = i+1; j < n; j++)

 if (a[j] < a[m_idx])

  m_idx = j;

  // swap the smallest element with left most element

  t=a[m_idx];

  a[m_idx]=a[i];

  a[i]=t;

}

}

// Driver function

int main()

{

// variable

int n;

cout<<"Enter the number of elements of array:";

// read the value of n

cin>>n;

// declare the array of size n

int arr[n];

cout<<"Enter the elements of array:";

// read the elements of array

for(int a=0;a<n;a++)

{

   cin>>arr[a];

}

// call the function to perform selection Sort

selectionSort(arr, n);

cout << "Sorted array: \n";

// print the sorted array

for (int i=0; i < n; i++)

cout << arr[i] << " ";

return 0;

}

Explanation:

Read the number of elements in the array and assign it to variable "n".Then read  n elements of the array.Call the function selectionSort() with parameter arr and  n.In this function find the smallest element and swap it with left most element  or the array.This is how selection sort work.At the end of for loop, array will  be sorted.

Output:

Enter the number of elements of array:6                                                                                    

Enter the elements of array:34 56 1 4 12 23                                                                                

Sorted array:                                                                                                              

1 4 12 23 34 56