What is wrong with my function for Selection sort?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Laya Maheshwari

    #1

    What is wrong with my function for Selection sort?

    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 -

    Code:
    void selection(int a[], int size)
    {
     int small, pos=0, temp, flag=0;
     for(i=0;i<(size-1);i++)
    	{
    	 small=a[i];
    	 for(j=i+1;j<size;j++)
    		{
    		 if(a[j]<small)
    			{
    			 flag=1;
    			 small=a[j];
    			 pos=j;
    			}
    		 else flag=0;
    		}
    	 if(flag=1)
    		{
    		 temp=a[i];
    		 a[i]=a[pos];
    		 a[pos]=temp;
    		}
    	 cout<<"\nArray after Pass "<<i+1<<" is - ";
    	 for(int k=0;k<size;k++)
    		cout<<a[k]<<" ";
    	}
     cout<<"\n\nThe finished and sorted array is as follows...\n\n";
     display(a,size);
     return;
    }
    Last edited by Frinavale; Oct 7 '10, 05:18 PM. Reason: Moved the question above the code so that people could understand the problem before having a bunch of code to look at.
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    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.

    Comment

    • Laya Maheshwari

      #3
      Hi. I've made that change. I've turned it to "if(flag==1 )". It is still showing the error.

      Comment

      • Alex T
        New Member
        • Oct 2010
        • 29

        #4
        Can you elaborate on how your program works, using comments in your code?

        Comment

        • newb16
          Contributor
          • Jul 2008
          • 687

          #5
          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.

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            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.

            Comment

            Working...