Thread: Selection Sort

  1. #1
    Registered User Andersonsacanno's Avatar
    Join Date
    Oct 2012
    Posts
    25

    Selection Sort

    Hello i have recently started programming in C and have managed to put together my first selection sort program.

    Code:
    #include <stdio.h>
    #include <conio.h>
    int sort(int a[], int x)
    {
    int i, j, spot;
     for (i = 0; i > x; i++)
     {
      
      for(j=i; j < 0; j--)
      {
       if (a[j] > a[j+1])
       {
       spot = a[j];
          a[j] = a[j+1];
       a[j+1] = spot;
       }
      }
     }
     return 0;
    }
      int main()  
      {  
      
          int a[100],x,i;  
      
            
      
          printf(" Spots in array: \n ");  
          scanf("%d",&x);  
      
          for( i=0;i<x;i++)  
      { 
          printf("\n\n Spot %d in array : ",i+1);  
                  scanf("%d",&a[i]);  
      }  
      
           sort(a,x);
      
           printf("\n\n\n\n\n iSort \n\n");  
           for( i=0;i<x;i++)
           {
           printf("%d\n",a[i]);  
           }
      
      system("Pause");
      }
    Everything seems to work besides the actual sort? Can someone more experienced please show me what I am doing wrong.


    Thanks.

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    The pseudocode Selection sort - Wikipedia, the free encyclopedia

    At your code
    Code:
    for (i = 0; i > x; i++)
    This is your initial loop in the function.Will the code flow enter it?

  3. #3
    Registered User Andersonsacanno's Avatar
    Join Date
    Oct 2012
    Posts
    25
    wouldn't using j = i in the second loop allow the data in my sort function to pass through the original for loop after each pass? Is this what you are refering too?

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    in the first iteration of the loop 'for (i = 0; i > x; i++)' , i == 0. look closely at the 'while' condition in your loop. will i ever be greater than x? and if it is, will the loop terminate?

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    You call the function sort,where you pass as parameters the array and the size of the array.You do not check if the input number for x is actually only positive, but ok, for now let's say that you trust the user.Let's assume that you type 5 for x.
    So you call your sort function with second argument x,which is equal to 5.
    Go to the function now,which is this
    Code:
    int sort(int a[], int x)
    {
          int i, j, spot;
          for (i = 0; i > x; i++)
         {
                   .....
          .....
    }
    Remember that x holds value 5.So the above code is equivalent to the following :
    Code:
    int sort(int a[], int 5)
    {
          int i, j, spot;
          for (i = 0; i > 5; i++)
         {
                   .....
          .....
    }
    and now focus in the line of for loop conditions.
    Code:
    for (i = 0; i > 5; i++)
    You set i to zero.And then you say,if i is greater than five,execute the body of the outer loop.In other words you say that if 0 is greater than five,execute the body of the outer loop.
    Of course 0 is not greater than 5,so your code inside this loop will never be executed.

    Idea : Zero is less than 5,so maybe set i<5,thus i<x..
    Last edited by std10093; 11-08-2012 at 06:44 PM.

  6. #6
    Registered User Andersonsacanno's Avatar
    Join Date
    Oct 2012
    Posts
    25
    My mistake on the second expression of the for loop need to be more careful obviously..

    Code:
    for (i = 0; i < x; i++) //quits when i is larger than x
     {
      
      for(j=i; j < x; i--) // isn't this wrong as well?
      {
       if (a[j] > a[j+1])
       {
       spot = a[j];
          a[j] = a[j+1];
       a[j+1] = spot;
       }
      }
     }
    Shouldn't my inner for loop have j++ for the update expression? If i starts out at zero; the loop will continue until j is larger than x; and we minus 1 each pass == terminates the loop.


    Code:
    for (i = 0; i < x; i++)
     {
      
      for(j=i; j < x; j++)
      {
       if (a[j] > a[j+1])
       {
       spot = a[j];
          a[j] = a[j+1];
       a[j+1] = spot;
       }
      }
     }
    Although we are making headway (The numbers jumble and for some reason result with a 0 in the middle of the array out of nowhere), we are still not sorting in the order I intend.

  7. #7
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Code:
    for(j=i; j < x; j++)
      {
       if (a[j] > a[j+1])
       .....
    What will happen in the if condition when j gets the value of x-1?

  8. #8
    Registered User Andersonsacanno's Avatar
    Join Date
    Oct 2012
    Posts
    25
    I'm sorry std10093 I'm lost with that statement. I have no idea how to iterate what you are asking me. Why would j have a value of x-1?

  9. #9
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Do not be sorry.You are honest.You try.I appreciate that
    See post number 8 from this thread Simple c programming
    When j gets the value of x-1 then in the if statement you will have this
    Code:
    if(a[x-1] > a[x])
    Arrays start indexing at zero and finish at sizeOfArray-1, so a[x] is out of borders.That i think explains the zero.You were just lucky not to get a segmentation fault.
    Maybe what you written here is not selection sort.Look the link i provided in post number two of this post for the pseudocode of it

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I don't know what that is, but it's certainly not selection sort. In selection sort, you repeatedly scan over the values of the array, and find the smallest value. Then you place that one value, and repeat until the array is all sorted.

    A slow sorter to be sure.

    Code:
    int min;
    int temp;
    
    for (i = 0; i < x-1; i++)  //x-1, same as Substitution sort on outer loop
     {
      
       min = a[i]; //  
      for(j=i+1; j < x; j++)  //i+1, also same as Substitution sort
      {
         //if (a[j] > a[j+1]) this is bubble sort!
         if(a[j] < a[min] 
         {  
            min = j;
         } 
      }
      if(min != i) {
         temp = a[i];
         a[i] = a[min];
         a[min] = temp;
      }
    }
    I don't use Selection sort but once in a blue moon, so this might not be right, but it's close.


    What will happen in the if condition when j gets the value of x-1?[/QUOTE]

  11. #11
    Registered User Andersonsacanno's Avatar
    Join Date
    Oct 2012
    Posts
    25
    Code:
    #include <stdio.h>
    #include <conio.h>
     
    
    void swap (int *a, int *b) 
    {
    int temp;
    
    temp = *a;
    *a = *b;
    *b = temp;
    }
    int sort(int a[], int x)
    {
    int i, j;
     for (i = 0; i < x-1; i++)
     {
      
     
      for(j=i; j < x-1; j++)
     
      { 
            printf(" if %d > %d \n",a[j], a[j+1]);
       if (a[j] > a[j+1])
       {
            printf("then swap them");
       swap(&a[j], &a[j+1]);
       }
      }
     }
     
    }
      int main()  
      {  
      
          int a[100],x,i;  
      
            
      
          printf(" Spots in array: \n ");  
          scanf("%d",&x);  
      
          for( i=0;i<x;i++)  
      { 
          printf("\n\n Spot %d in array : ",i+1);  
                  scanf("%d",&a[i]);  
      }  
      
           sort(&a[0],x);
      
           printf("\n\n\n\n\n iSort \n\n");  
           for( i=0;i<x;i++)
           {
           printf("%d\n",a[i]);  
           }
      
      system("Pause");
      }
    Success!

    A big problem in this coding was using pointers for the sorting function and calling it in main().
    another problem was not having the exact logic behind a selection sort. Adding print statements in loops can help a lot. Thanks to everyone for their help here.

    std10093 You had mentioned earlier about trusting a user. I'm guessing your talking about a flaw I have in this. Although this is simple I would like to start implementing security features early on. Any advice on improvement is appreciated.

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Your sort is a not a Selection sort, I would call it a Bubble sort, although I'm no expert.

    In a Selection sort, you look for the smallest value of the array, in the inner loop, and assign the index of that minimum value, to a variable (call it min). Not the value, the index.

    Then, outside the inner for loop, you test whether min is the same index as i, -- if it is, no swaps are needed. If min != i, then you swap a[min] with a[i].

    Nothing wrong with a good sort you came up with - but if you are assigned to do a Selection sort, you need to review my previous post.
    Last edited by Adak; 11-08-2012 at 10:18 PM.

  13. #13
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Quote Originally Posted by Andersonsacanno View Post
    [code]
    std10093 You had mentioned earlier about trusting a user. I'm guessing your talking about a flaw I have in this. Although this is simple I would like to start implementing security features early on. Any advice on improvement is appreciated.
    You let the user input the size of spots.If the user inputs a negative or zero number,then you will set the number of spots to a negative or zero number , which does not make any sense. Remember that he may by accident input that number.It would be nice to inform him.In addition inform him that no sorting is going to take place.
    You do not have a security issue here, but in general you should always check if the input is satisfying some requirements.Consider this example.We have an array of ten elements and we want the user to input a number, so that we access the element in this specific index.
    Code:
    #include <stdio.h>
    
    int main(void)
    {
         int a[5];
         int i;
         int request;
      
         for( i = 0 ; i < 5 ; i++)
         {
                 a[i] = 7;
          }
      
          printf("Please type the number of element you want to access.Indexing starts from zero\n"); 
          scanf("%d",&request);
    
          printf("Element in index %d is %d \n",request,a[request]);
    
          return 0;
    }
    What will happen if by accident or for other reason i type -1?You are going to access the -1-th element of array a, in other words a[-1], which of course is an error.
    So, modify the code to this :
    Code:
    #include <stdio.h>
    
    int main(void)
    {
         int a[5];
         int i;
         int request;
      
         for( i = 0 ; i < 5 ; i++)
         {
                 a[i] = 7;
          }
      
          do{
              printf("Please type the number of element you want to access.Indexing starts from zero\nNotice that input must be a positive, non-zero number\n"); 
              scanf("%d",&request);
          }while(request<=0);
    
          printf("Element in index %d is %d \n",request,a[request]);
    
          return 0;
    }
    But what if the user inputs an index greater than the index of last element(in this case 4) ?Again, an error is likely to occur .
    Again modify the code to this
    Code:
    #include <stdio.h>
    
    int main(void)
    {
         int a[5];
         int i;
         int request;
    
         for( i = 0 ; i < 5 ; i++)
         {
                 a[i] = 7;
          }
    
          do{
              printf("Please type the number of element you want to access.\n");
              printf("Input must be in range of 0 to 4.\n");
              scanf("%d",&request);
          }while(request<=0 || request>4);
    
          printf("Element in index %d is %d \n",request,a[request]);
    
          return 0;
    }
    
    PS - i am telling you from the start that this is not selection sort.Adak also states that.
    The do while loop will force the user to input again, if "wrong" input is given.

  14. #14
    Registered User Andersonsacanno's Avatar
    Join Date
    Oct 2012
    Posts
    25
    Wow guys thanks for all the help!

  15. #15
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Our pleasure!I also guess that this is your first thread,so welcome to the forum

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Selection Sort
    By Drew in forum C++ Programming
    Replies: 16
    Last Post: 09-18-2003, 07:19 AM
  2. merge sort and selection sort and time spent on both
    By misswaleleia in forum C Programming
    Replies: 3
    Last Post: 06-04-2003, 02:24 PM
  3. Selection Sort
    By volk in forum C++ Programming
    Replies: 3
    Last Post: 05-08-2003, 06:54 AM
  4. Selection Sort
    By Bleueyes515 in forum C++ Programming
    Replies: 3
    Last Post: 09-30-2002, 08:33 PM
  5. Selection-sort
    By Nutshell in forum C Programming
    Replies: 10
    Last Post: 01-11-2002, 04:32 AM