Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

modify the selection sort algorithm to sort the first k elements of the array (t

ID: 3664653 • Letter: M

Question

modify the selection sort algorithm to sort the first k elements of the array (the value of k will be entered by the user). Your algorithm must run in O(nk) time.

I have this so far:

#include <algorithm>

#include <utility>

#include <iostream>

int main()

{

   const int size = 10;

   int array [size] ={ };

   std::cout<< "Enter the values you want sorted: " ;

   std::cin>> array[size];

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

   {

       int small = i;

       for (int current = i +1; current < size ; current++)

       {

           if ( array[current] < array[ small])

               small = current;

       }

       std::swap(array[i], array[small]);

   }

   for ( int j= 0 ; j<size; j++)

   std::cout<< array[j]<< ' ';

return 0;

}

My cin>> doesn't work and gives me an error. Thoughts?

Explanation / Answer

Answer -

#include <algorithm>
#include <utility>
#include <iostream>

int main()
{
const int size = 10;
int k,array [size];
std::cout<<"Enter the values you want sorted: " ;
for ( int j=0; j<size; j++)
{
std::cin>>array[j];
}
std::cout<<" Entered Array: " ;
for ( int j= 0 ; j<size; j++)
std::cout<< array[j]<< ' ';
std::cout<<" Enter count of values in array to be sorted " ;
std::cin>>k;
for ( int i=0; i<k; i++)
{
int small = i;

for (int current = i +1; current < k ; current++)
{
if ( array[current] < array[ small])
small = current;
}
std::swap(array[i], array[small]);
}
for ( int j= 0 ; j<size; j++)
std::cout<< array[j]<< ' ';
return 0;
}

Your cin>>array[size] did not work because it is an array and you were having input directly not by loop in every array[j].