I have written this code for insertion sort but, its not generating any output.
could you please tell me whats wrong in this code

Thanks!!

#include<stdio.h>
#include<conio.h>

int main()
{
    int arr[25]={1,2,3,4,5,6,7,8,9,21,15,16,18,22,24,72,77,79,91,62,27,35,11,90,110},i,temp=0,j,a;
    int *p;
    
    for(i=0;i<25;i++)
    {
        if (arr[i]>arr[i+1])
        {
         temp=arr[i];
         arr[i]=arr[i+1];
         arr[i+1]=temp;
      
         p=&arr[i];
        
             while(i!=0)
             {
               if(*p<arr[i-1])
                {
                  temp=*p;
                  *p=arr[i-1];
                  arr[i-1]=temp;
                }
                else
                { 
                 continue;
                }
                 i--;
             }
        }
        else
        {
         continue;
        }
    }
    
    for(i=0;i<25;i++)
    {
     printf("\n %d",arr[i]);
    }
     
     getch();
}

Your code is very verbose, and overly complex. Try and keep it short, simpler, and thus faster. Like this:

void insertionSort(int A[], int lo, int hi) {
  int i, j, val; 
    
  for(i=lo+1;i<hi;i++) {  
    val = A[i];
    j = i-1;
    while(A[j] > val) {
      A[j + 1] = A[j];
      --j;
      if(j<0) break;
    }   
    A[j+1] = val;
  }

  puts("\nAfter Insertion Sort:\n");
  for(i=lo;i<hi;i++)
    printf(" %2d ",A[i]);
  getch();


}

Thanks for the reply.
I couldn't understand this program, Could you plz elaborate.

Thanks again

Try calling it with an int array A[], where lo is zero, and hi is the top of the array (the index, not the value it holds).

It does the same thing as your program, but more concisely. Yours used a pointer *p where this one uses a variable val (for value). More to the point, it uses just one pair of nested loops, to do everything. It is quick, especially for small and mid sized number of items (say to 100 or 200), particularly so when the items are almost already sorted - then it blazes!

I use it to speed up Quicksort, when the sub arrays Quicksort is working with, become small enough. Insertion sort, finishes them off - very nice. Also, any small to medium sized sorting job. Much faster than bubble sort, trust me! ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.