Recursive Insertion sort

Discussion in 'C' started by ladybird, Feb 10, 2011.

  1. ladybird

    ladybird New Member

    Joined:
    Feb 10, 2011
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    I'm looking for recursive version of Insertion sort code. can anyone tell me how to write it?!
     
  2. DRK

    DRK New Member

    Joined:
    Apr 13, 2012
    Messages:
    44
    Likes Received:
    3
    Trophy Points:
    0
    Code:
    void checkAndSwap(int *array, int j, int value)
    {
    	int done = 0;
    	if (array[j] > value)
    	{
    		array[j + 1] = array[j];
    		if (--j < 0)
    		{
    			done = 1;
    		}
    	}
    	else
    	{
    		done = 1;
    	}
    	if (done)
    	{
    		array[j + 1] = value;
    	}
    	else
    	{
    		checkAndSwap(array, j, value);
    	}
    
    }
    
    void insertionSort(int *array, int length)
    {
    	static int i;
    	int j = i, value;
    	if (++i < length)
    	{
    		value = array[i];
    		checkAndSwap(array, j, value);
    		insertionSort(array, length);
    	}
    	else
    	{
    		i = 0;
    	}
    }
    Example of use:
    Code:
    #define LENGTH 8
    int array[LENGTH] = { 5, 7, 0, 3, 4, 2, 6, 1 };
    insertionSort(array, LENGTH);
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice