selection sort compiles but does not sort the array as desired
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
#include<iostream>
using namespace std;
void select(int *const,int const,bool(*)(int,int));
void swap(int *const,int *const);
bool ascending (int,int);
bool descending(int,int);
int main()
{
const int arraysize=5;
int a[arraysize]={23,1,34,12,7};
int order;
cout<<"\nunsorted array is:";
for(int i=0;i<arraysize;i++)
cout<<" "<<a[i];
cout<<endl;
cout<<"\n enter order 1 for listing of elements in ascending order \n 2 for listing in descending order "<<endl;
cin>>order;
if(order==1)
{
cout<<"\n array in ascending order is :";
select(a,arraysize,ascending);
}
else
{
cout<<"\n array in descending order is :";
select(a,arraysize,descending);
}
for(int i=0;i<arraysize;i++)
cout<<" "<<a[i];
cout<<endl;
return 0;
}
void select(int *const arr,const int size,bool (*compare)(int ,int ))
{
int smallorlargest;
for(int i=0;i<size;i++)
{
smallorlargest=i;
for(int j=i+1;j<size;j++)
{
if(!(*compare)( arr[smallorlargest],arr[j]))
{
smallorlargest=j;
}
}
swap( &arr[smallorlargest],&arr[i] );
}
}
void swap(int *const a,int *const b)
{
int x=*a;
*a=*b;
*b=x;
}
bool ascending(int x,int y)
{
return x < y;
}
bool descending(int p,int q)
{
return p > q;
}
The above code is the correct version of your code. The bold line should be outside the inner for loop and not inside the inner for loop as in your code.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.