Thread: C Sort

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    2
    Rep Power
    0

    Exclamation C Sort


    Hey buds.. I am newbie in C language programming.. I was writing a code for program featuring insertion sort.. Everything seems fine but I gut garbage values in the end instead of sorted values... Hope anyone can help debugging it... Whats the mistake in it..

    Code:
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
    clrscr();
    int n,l,a[11],p;
      do
      {
      printf("Number of Entries: ");
      scanf("%d",&n);
      if (n>10)
        printf("Entry should not be greater than 10.\nRetry!\n");
      if (n<2)
        printf("Entry should not be less than 2.\nRetry!\n");
      }
      while (n>10 || n<2);
    printf("\n");
    for(l=1;l<=n;l++)
      {
      printf("Entry #%d:",l);
      scanf("%d",&a[l]);
      }
    printf("\n\nSorted Order:\n");
    for (l=2;l<=n;l++)
      {
      if (a[l]<a[l-1])
        {
        for(p=l;p>=2;p--)
          {
          a[p]=a[0];
          a[p-1]=a[p];
          a[0]=a[p-1];
          if (a[p]>a[p-1])
          p=1;
          }
        }
      }
    for(l=1;l<=n;l++)
    printf("%d\n",a[l]);
    getch();
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,407
    Rep Power
    1871
    for(l=1;l<=n;l++)
    vs.
    for (l=2;l<=n;l++)
    vs.
    a[p]=a[0];

    You need to be clear about which array elements you're using.

    You read data in starting from element 1.
    You start sorting at element 2.
    Somehow, you involve the uninitialised element 0 in the actual sorting.

    Your first correction would be to make both loops run as follows
    for ( l = 0 ; l < n ; l++ )


    By the way, main returns int, not void.
    Success is indicated by having a return 0; at the end of main.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    2
    Rep Power
    0
    Thanx bud for replying.. I have sorted out my mistake.. The problem was in the swapping code lines..

    Comments on this post

    • Lux Perpetua disagrees : pointless locking of thread

IMN logo majestic logo threadwatch logo seochat tools logo