Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Selection sort find "kth" smallest element

$
0
0
I have been asked to create a function based on selection sort to find the kth smallest element in an arbitrary array of integers.

I used the standard selection sort which sorts the array and then uses input to output what integer they are requesting to find.

It works correctly, I just feel as though it is a very "lame" inefficient program. I know there is a way to cut a few corners and find the answer prior to the sort, but i cannot figure it out.

I was also asked to state why selection sort is a better method then insertion sort for this task?


Here is my code:
 int main()
{
const int nSize = 5;
int A[nSize] = { 30, 5, 200, 151, 40 };


for (int nStartIndex = 0; nStartIndex < nSize; nStartIndex++)
{
   
    int nSmallestIndex = nStartIndex;
 
    for (int nCurrentIndex = nStartIndex + 1; nCurrentIndex < nSize; nCurrentIndex++)
    {
  
        if (A[nCurrentIndex] < A[nSmallestIndex])
      
            nSmallestIndex = nCurrentIndex;
    }
 
  
    swap(A[nStartIndex], A[nSmallestIndex]);
	

}
int j;
cout<<"Enter the kth smallest number you want:"<<endl;
cin>>j;
cout<<endl<<A[j-1]<<" is the "<<j<<" smallest element ";
}

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>