Reputation: 31
I wrote a selection-sort algorithm but it didn't work. I cannot find my mistake. Can anyone help me?
#include <stdio.h>
int main () {
int array[100],i,j,position,size,swap;
printf("Enter number of integers\n");
scanf("%d",&size);
printf("Enter %d integers\n",size);
for(i=0;i<size;i++){
scanf("%d",&array[i]);
}
for(i=0;i<size;i++){
position=i;
for(j=i;j<size;j++){
if(array[position]>array[j]){
position=j;
}
if(position!=i){
swap=array[i];
array[i]=array[position];
array[position]=swap;
}
}
}
printf("Sorted list in ascending order\n");
for(i=0;i<size;i++){
printf("%d\n",array[i]);
}
return 0;
}
Upvotes: 0
Views: 187
Reputation: 306
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.
So the swap needs to happen after you have found the correct position i.e. happening after your for loop is over. So if you switch the if block after the j loop ends, the code should work.
for(i=0;i<size;i++){
position=i;
for(j=i;j<size;j++){
if(array[position]>array[j]){
position=j;
}
}
if(position!=i){
swap=array[i];
array[i]=array[position];
array[position]=swap;
}
}
Upvotes: 0