By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,961 Members | 1,332 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,961 IT Pros & Developers. It's quick & easy.

What is wrong with my function for Selection sort?

P: n/a
The function works fine if the "small" I have chosen, ie, a[i], is *not* the smallest element in the array. It swaps and sorts just fine. But when the "small", ie, a[i], is the smallest element in the array already, then it goes bonkers, still substituting it with the previous value of "pos".

How do I remedy this?

Here is the code I have written -

Expand|Select|Wrap|Line Numbers
  1. void selection(int a[], int size)
  2. {
  3.  int small, pos=0, temp, flag=0;
  4.  for(i=0;i<(size-1);i++)
  5.     {
  6.      small=a[i];
  7.      for(j=i+1;j<size;j++)
  8.         {
  9.          if(a[j]<small)
  10.             {
  11.              flag=1;
  12.              small=a[j];
  13.              pos=j;
  14.             }
  15.          else flag=0;
  16.         }
  17.      if(flag=1)
  18.         {
  19.          temp=a[i];
  20.          a[i]=a[pos];
  21.          a[pos]=temp;
  22.         }
  23.      cout<<"\nArray after Pass "<<i+1<<" is - ";
  24.      for(int k=0;k<size;k++)
  25.         cout<<a[k]<<" ";
  26.     }
  27.  cout<<"\n\nThe finished and sorted array is as follows...\n\n";
  28.  display(a,size);
  29.  return;
  30. }
Oct 7 '10 #1
Share this Question
Share on Google+
5 Replies


Expert 100+
P: 2,396
Line 17 should be "if(flag==1)".

I haven't taken the time to truly understand your code, but I'm suspicious of how flag is used in lines 7-16. Line 15 will reset the flag, causing the program to forget that it was set by an earlier pass through the loop.
Oct 7 '10 #2

P: n/a
Hi. I've made that change. I've turned it to "if(flag==1)". It is still showing the error.
Oct 7 '10 #3

P: 29
Can you elaborate on how your program works, using comments in your code?
Oct 8 '10 #4

100+
P: 687
You have the error in determining if the flag should be set. It is set only if the last element of the array is less than the smallest element found, else it is 0.
Oct 8 '10 #5

Expert 100+
P: 2,396
Please take a moment to describe the algorithm for Selection Sort using natural language (not computer language). Ideally, this description would go in your source code as comments.
Oct 8 '10 #6

Post your reply

Sign in to post your reply or Sign up for a free account.