1

I'm trying to create a simple(?) selection sort program in C that selects the largest integer of an integer array and places it in the location a[n-1], places the second largest number in a[n-2], etc until the smallest number is placed in a[0]. I've run through the below code on paper and it seems like it should work, but when I compile it I'm getting faulty results. Am I missing something obvious?

/* The program implements selection sort*/

#include <stdio.h>
#include "simpio.h"

#define n 5

void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
void PrintArray(int a[]);

main()
{
      int a[n];
      GetArray(a);
      SelectionSort(a);
      PrintArray(a);
      getchar();
}

void GetArray(int a[])
{
     int i;
     for(i=0;i<n;i++)
     {
       printf("Enter integer# %d", i+1);
       a[i]=GetInteger();
     }
}

void SelectionSort(int a[])
{
     int i, max;
     for(i=0;i<n;i++)
     {
           max=FindMax(a,i);
           swap(a,max,(n-1-i));
     }     
}

int FindMax(int a[], int high)
{
    int i, index;
    index=high;
    for(i=high;i<n;i++)
    {
       if(a[i]>a[index])
          index=i;
    }
    return index;
}

void swap(int a[], int p1, int p2)
{
     int temp;
     temp=a[p2];
     a[p2]=a[p1];
     a[p1]=temp;
}

void PrintArray(int a[])
{
     int i;
     for(i=0;i<n;i++)
       printf("a[%d]=%d\n", i, a[i]);
}
6
  • 3
    Don't try it on paper, run it through the debugger until you find the point where its behaviour diverges from what you expect. Commented Feb 22, 2012 at 1:37
  • I agree with Oli - also, you'll generally get a better response from questions here if you can narrow down where the problem is. A debugger or print statements will help you do this - and you may even find the problem without needing to ask :) Commented Feb 22, 2012 at 1:43
  • 1
    "I'm getting faulty results." What input creates what result? Give sample input, and show what you actually get. Commented Feb 22, 2012 at 1:46
  • This is why you should just bite the bullet and learn how to use qsort :-) Commented Feb 22, 2012 at 1:52
  • @TimothyJones Could you clarify what you mean by print statements? I haven't really debugged with that method and I'm not quite sure if I see how it could be applied here... (Sorry if this has an obvious answer, I'm a little new to programming). Commented Feb 22, 2012 at 2:04

5 Answers 5

2

Selection sort is process of comparing minimum element from the list and placing from the least index. Now consider below code snippet.

public void selectionSort(int[] elements) {
    
    for(int i=0;i<elements.length;i++) {
        int minPosition = i;
        for(int j=i+1;j<elements.length;j++) {              
            if(elements[minPosition]>elements[j])
                minPosition = j;                
        }

        int temp = elements[i];
        elements[i] = elements[minPosition];
        elements[minPosition] = temp;       
    }
}

Thanks for reading, let me know feedback to improve from myside

Sign up to request clarification or add additional context in comments.

Comments

1

Change these method to:

void SelectionSort(int a[])
{
     int i, max;
     for(i=0;i<n;i++)
     {
           max=FindMax(a,n-i-1);
           swap(a,max,n-i-1);
     }     
}

int FindMax(int a[], int high)
{
    int i, index;
    index=high;
    for(i=0;i<high;i++)
    {
       if(a[i]>a[index])
          index=i;
    }
    return index;
}

I actually tested my answer and it works.

2 Comments

Off topic, but are you from the PhpBB support forum? I think I recognize you :-) But that seems to be working for me, I'll have to look at my previous code and see where I went wrong.
Nope - never even done any real PHP. But glad I could help : )
0

Shouldn't:

       max=FindMax(a,i);
       swap(a,max,(n-1-i));

Be:

       max=FindMax(a,i);
       swap(a,max,i);

otherwise, next time through the loop, you'll find the same max value in the top position in the array.

2 Comments

But then wouldn't the highest number would be put in a[0], etc?
That's true. Your current version has the SelectionSort for decending sort, but the FindMax for ascending sort. Daniel's answer fixes the FindMax for you.
0

A very basic implementation of selection sort

#include<stdio.h>
main()
{
       int i,j,n=7,a[]={1,2,5,3,8,9,5},key;
       for(j=1;j<n;j++)
       {
                       key=a[j];    //a[j] is the new element to be added to the sorted
                                    //sequence
                       i=j-1;       
                       while(i>=0 && key<a[i]) //traverse through the sorted sequence
                       {a[i+1]=a[i];i--;}      //until the place of key is found
                       a[i+1]=key;             
       }
       for (j=0;j<n;j++)
       printf("%d",a[j]);
}

Comments

-1
#include<stdio.h>
#include<conio.h>
int removex(int arr[],int small,int n)
{
    int i=0;
    for(;i<n;i++)
        if(arr[i]==small)  //searching that no to delete
            break;
    for(;i<n-1;i++)
        arr[i]=arr[i+1]; //delete by overloading no
    return n-1;
}
void selectSort(int arr[],int sort[],int n)
{
    int j=0,k=0,small;
    while(n!=0)
    {
        small=arr[0];
        for(j=0;j<n;j++)
            if(arr[j]<small)
                small=arr[j]; //finding smallest no
        sort[k++]=small;
        n=removex(arr,small,n);  //removing that from list as we included that no into sorted list
    }
}
void main()
{
    int arr[10],arr2[10],i,n;
    clrscr();
    printf("Enter how many elements");
    scanf("%d",&n);
    for(i=0;i<n;i++)
        scanf("%d",&arr[i]);
    selectSort(arr,arr2,n);
    printf("sorted list is\n");
    for(i=0;i<n;i++)
        printf("%d\n",arr2[i]);

    getch();
}

4 Comments

Explanation please.
Why add another answer to a 4 year old question that already has an accepted answer? Especially if your new answer is just a dump of code with no explanation.
<conio.h> is not a standard header; void main should be int main; clrscr and getch aren't standard functions; you should never ignore scanf's return value (actually, you should never use scanf for user input in the first place); that's also a potential buffer overflow.
@melpomene Thank You Sir for feedback

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.