September 2018 - 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 and user input

September 23, 2018 0

C program for insertion sort with function and user input

// C program for insertion sort with function and user input
#include 
//prototype declaration for functions
void insertionSort(int arr[], int n);
void printArray(int arr[], int n);

int main()
{    //taking the input for array length
    printf("How many elements do you want to input?: ");
    int n;
    scanf("%d",&n);
    //Declaration of array and relevant variables
    int arr[n],i;
    for(i=0; i    {
        printf("Please input the element: ");
        scanf("%d",&arr[i]);
        // sorting the array
        insertionSort(arr, i);
    }
    //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");
}

Read More

C program for insertion sort with function

September 23, 2018 0

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");
}
Read More

Post Top Ad