سؤال

void main()
{
  char name[5][10],temp[10];
  int i,j;
  for(i=0;i<5;i++)
{
 printf("\nEnter the name of student:");
 scanf("%s",name[i]);
}
for(i=0;i<(5-1);i++)
{
  for(j=i+1;j<5;j++)
  {
    if(strcmp(name[i],name[j])>0)
  {
    strcpy(temp,name[i]);
    strcpy(name[i],name[j]);
    strcpy(name[j],temp);
   }
  }
}
printf("\n the name of student is:");
for(i=0;i<5;i++)
{
 printf("\n%s",name[i]);
}
 getch();
}

I couldn't figure out the difference between insertion sort and selection sort ..Is this code following selection algorithm or Insertion ?

هل كانت مفيدة؟

المحلول

It is a specially slow version of selection sort.

It looks like a bubble sort, but a bubble sort would compare/swap the elements at positions j-1 and j, which are contiguous. You compare/swap the elements at positions i and j.

During every iteration of the outer loop, i remains constant while j advances from i+1 to the end. Thus, you end up having the element with the minimum value at position i.

You probably make a lot of unnecessary movements. A proper selection sort would search for the minimum value without moving anything. Then it would swap that minimum value with the value at position i. Therefore, it would perform only one swap per element in the array.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top