Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why isnt the code not working any one help?

+1 vote
asked Aug 22, 2021 by Purna Sai (130 points)
#include<iostream>
using namespace std;
void selectionsort()
{ int i,j,key,a[100],n;
cout<<"enter the value of n";
cin>>n;
cout<<endl<<"enter the array  elements";
for(i=0;i<n;i++)
{
    cin>>a[i];
}
for(i=1;i<n;i++)
{
    key=a[i];
    j=i-1;
    while(j>=0 && a[j]>key)
    {
        a[j+1]=a[j];
         j=j-1;
    }
   a[i+1]=key;
}
for(i=0;i<n;i++)
{
    cout<<a[i];
}
}
int main()
{
    selectionsort();
}

1 Answer

0 votes
answered Sep 22, 2021 by Peter Minarik (101,420 points)

You incorrectly implemented the selection sort algorithm. Please, read how it should work: https://en.wikipedia.org/wiki/Selection_sort

Some highlights in your code:

  • You're supposed to swap elements, not overwrite with an existing value
  • You should start from the 0th element, not from the 1st when you sort
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...