C program for insertion sort with function - All About Technology! "

All About Technology!

All About Technology! A complete guide to latest technology and science.

Sunday, September 23, 2018

C program for insertion sort with function

C program for insertion sort with function


// C program for insertion sort with function
#include 
#include 

//prototype declaration for functions
void insertionSort(int arr[], int n);
void printArray(int arr[], int n);

int main()
{
    int arr[] = {12, 11, 13, 5, 6};
    //calculating size of array
    int n = sizeof(arr)/sizeof(arr[0]);
    //int n =5;
    // sorting the array
    insertionSort(arr, n);
    //printing the array
    printArray(arr, n);

    return 0;
}

/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++)
    {

        j = i;

        while(j>0 && arr[j-1]>arr[j])
        {
            //swapping the elements
            int temp = arr[j-1];
            arr[j-1]=arr[j];
            arr[j]=temp;
            j--;
        }

    }
}

//Function to print the array
void printArray(int arr[], int n)
{
    int i;
    for (i=0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

No comments:

Post Top Ad