Knowee
Questions
Features
Study Tools

C program for Insertion sort and solve the tracing for any 2 example elements on your own.

Question

C program for Insertion sort and solve the tracing for any 2 example elements on your own.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple implementation of Insertion Sort in C:

#include <stdio.h>

void insertionSort(int arr[], int n) {
   int i, key, j;
   for (i = 1; i < n; i++) {
       key = arr[i];
       j = i - 1;

       while (j >= 0 && arr[j] > key) {
           arr[j + 1] = arr[j];
           j = j - 1;
       }
       arr[j + 1] = key;
   }
}

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

int main() {
   int arr[] = {12, 11, 13, 5, 6};
   int n = sizeof(arr) / sizeof(arr[0]);

   insertionSort(arr, n);
   printArray(arr, n);

   return 0;
}

Now, let's trace the sorting process for the first two elements of the array {12, 11, 13, 5, 6}:

  1. In the first iteration, i = 1, key = arr[1] = 11, and j = i - 1 = 0. Since arr[j] = 12 is greater than key = 11, we move arr[j] to arr[j + 1], resulting in the array {12, 12, 13, 5, 6}. Then we decrease j by 1 to -1. Since j is no longer >= 0, we exit the while loop and set arr[j + 1] = key, resulting in the array {11, 12, 13, 5, 6}.

  2. In the second iteration, i = 2, key = arr[2] = 13, and j = i - 1 = 1. Since arr[j] = 12 is not greater than key = 13, we do not enter the while loop and directly set arr[j + 1] = key. The array remains {11, 12, 13, 5, 6}.

The rest of the array would be sorted in the subsequent iterations.

This problem has been solved

Similar Questions

Write an algorithm for insertion sort. Analyze insertion sort algorithmfor best case and worst case.

What will be the number of passes to sort the elements using insertion sort?14, 12,16, 6, 3, 10

The operation of processing each element in the list is known as ……a.sortingb.mergingc.insertingd.traversal

Which of the following algorithm pays the least attention to the ordering of the elements in the input list?Insertion sort Selection sort Quick sort None

time and space complexity write a program which satisfy order of n sorting_tracing stack que difference between stack and queue linked list (single do

1/2

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.