Reputation: 27
#include <stdio.h>
int main() {
int arr[5];
for(int i=0; i<5; i++)
scanf("%d",&arr[i]);
for(int i=0; i<5; i++)
{
int m=arr[i];
for(int j=i+1; j <5; j++)
{
if(m>arr[j])
{
arr[i]=arr[j];
arr[j]=m;
}
}
}
for(int i=0; i<5; i++)
printf("%d ",arr[i]);
return 0;
}
Why is this sorting program not working? Where is this program wrong? This program not sorting the array. Where is it wrong?
Upvotes: -2
Views: 94
Reputation: 311068
The problem is this if statement
if(m>arr[j])
{
arr[i]=arr[j];
arr[j]=m;
}
that does not update the value of the variable m
.
You need to write
if(m>arr[j])
{
arr[i]=arr[j];
arr[j]=m;
m = arr[i];
}
In fact the variable m
declared before the inner for loop is redundant. You could just write without using the variable m
if ( arr[j] < arr[i] )
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
The loops could be more efficient if to swap elements in the array only one time. For example
for ( int i = 0; i < 5; i++ )
{
int m = i;
for ( int j = i + 1; j < 5; j++ )
{
if ( arr[j] < arr[m] )
{
m = j;
}
}
if ( m != i )
{
int tmp = arr[i];
arr[i] = arr[m];
arr[m] = tmp;
}
}
You could write a separate function. For example
void selection_sort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t m = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[m] )
{
m = j;
}
}
if ( m != i )
{
int tmp = a[i];
a[i] = a[m];
a[m] = tmp;
}
}
}
and call it like
selection_sort( arr, 5 );
Upvotes: 2