Hey I am a student and i m performing selection sort in this way.
Is it proper way or not? if it is not proper, explain it why with reason.

#include<stdio.h>
#include<conio.h>
void selection(int a[],int n)
{
    int i,j,temp;
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=a[i];
            }
        }
    }
}

Why don't you think it's correct?

Member Avatar for atulgupta9

Let's assume the array a[] contains 5 elements=[9 1 7 2 6]
n=5
asssuming first iteration of outer loop i->0
i->0 j->1
9 > 1
a[]=[1 9 7 2 6]

i->0 j->2
1>7
false a[]=[1 9 7 2 6]

i->0 j->3
1>2
false a[]=[1 9 7 2 6]

i->0 j->4
1>6
false a[]=[1 9 7 2 6]

second iteration
i->1 j->2
7>9
false a[]=[1 7 9 2 6]

i->1 j->3
7>2
a[]=[1 2 9 7 6]

i->1 j->4
2>6
false a[]=[1 2 9 7 6]

third iteration
i->2 j->3
9>7
a[]=[1 2 7 9 6]

i->2 j->4
7>6
a[]=[1 2 6 9 7]

fourth iteration
i->3 j->4
9>7
a[]=[1 2 6 7 9]
**
fifth iteration i->4** not required
your code should work fine but there's just one problem as you might have understood through the above test run

just change the outer loop's terminating condition from i<n to i<n-1
and rest should do the job

Also it's obvious while you are bringing the lowest no. at the required position after each and every pass (when i increments).The no. of passes required will be n-1

ok ... i will improve this code. And thanks a lot.
Some books don't allow this code. And mostly books code selection sort with a help of variable min.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.