selection sort

#include<stdio.h>
#include<conio.h>
int main()
{
int arr[15],least_ele,j,n,i,index;
printf("enter size\n");
scanf("%d",&n);
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
least_ele=arr[i];
for(j=i;j<n;j++)
{
if(least_ele>arr[j])
least_ele=arr[j];
index=j;
}
if(least_ele!=arr[i])
{
arr[index]=arr[i];
arr[i]=least_ele;
}
}
printf("\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
getch();
}

not getting desired output...!!
if {} and j=i+1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[15],least_ele,j,n,i,index;
printf("enter size\n");
scanf("%d",&n);
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
least_ele=arr[i];
for(j=i+1;j<n;j++)
{
if(least_ele>arr[j])
{
least_ele=arr[j];
index=j;
}
}
if(least_ele!=arr[i])
{
arr[index]=arr[i];
arr[i]=least_ele;
}
}
printf("\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
getch();
}


PS:post codes like I posted
PS: It's useless if you don't indent it.
Always put your code inside code blocks , here is the correction :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[15],least_ele,j,n,i,index;
printf("enter size\n");
scanf("%d",&n);
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
{
	least_ele=arr[i];
	
	for(j=i;j<n;j++)
	{
		if(least_ele>arr[j]) 
		least_ele=arr[j];
		index=j;
	}

	if(least_ele<arr[i]) /* this if statement should swap only in case if least_ele is smaller than arr[i] 
                                         ( previously it was swapping it even when least_ele was greater than arr[i] ) */
	{
		arr[index]=arr[i];
		arr[i]=least_ele;
	}
}
printf("\n");
for(i=0;i<n;i++)
printf("%d\n",arr[i]);
getch();

return 0;
}

Last edited on
@xordux

line 18 and 19 should be enclosed in Braces {...}
at line 22 of your code three things can be done
1)what you did
2)What vgoel and I did(because least_ele is not going to be greater than arr[i])
3)No use of If condition.Just put index=i; at line 14 of your code.
Topic archived. No new replies allowed.