In: Computer Science
write a program in C language
Create a function to perform the insertion sort. Now the program will perform the following steps:
Code snippet:
1. Function Declaration
void displayArray(float *arr, int size); void sortArray(float *arr, int size);
2. Function definition
void displayArray(float *arr, int size){ printf("["); for (int i=0; i<size-1; i++) { printf("%f, ",arr[i]); } printf("%f]\n", arr[size-1]); }
3. Function call/invocation
displayArray(arr, N); sortArray(arr, N);
4. Dynamic memory allocation for array
float *arr = (float*) malloc(N * sizeof(float));
If you have any doubts, please give me comment...
#include <stdio.h>
#include <stdlib.h>
void displayArray(float *arr, int size);
void sortArray(float *arr, int size);
int main()
{
int N, i;
float *arr = NULL;
printf("Enter the number of array elements: ");
scanf("%d", &N);
arr = (float *)malloc(N * sizeof(float));
printf("Enter %d elements: ", N);
for (i = 0; i < N; i++)
{
scanf("%f", &arr[i]);
}
printf("Entered elements are: ");
displayArray(arr, N);
sortArray(arr, N);
printf("After sorting: ");
displayArray(arr, N);
return 0;
}
void displayArray(float *arr, int size)
{
printf("[");
for (int i = 0; i < size - 1; i++)
{
printf("%.1f, ", arr[i]);
}
printf("%.1f]\n", arr[size - 1]);
}
void sortArray(float *arr, int size)
{
int i, j;
float temp;
for (i = 1; i < size; i++)
{
temp = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > temp)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
}