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");
}
No comments:
Post a Comment