C

Insertion Sort in C

We can create a C program to sort the array elements using insertion sort. The insertion sort algorithm is only useful for small elements, as it takes more time to sort a large number of elements. Here is how the process works:


Source: Wikipedia.org

100-multiple-choice-questions-in-c-programming100 Multiple Choice Questions In C Programming – Part 1This collection of 100 Multiple Choice Questions and Answers (MCQs) In C Programming : Quizzes & Practice Tests with Answer focuses on “C Programming”.  …Read More
 

Insertion Sort in C
/* Insertion Sort in  */
 
#include <stdio.h>
#define SIZE 10
 
int main()
{ 
  int arr[10] = { 3, -2, 7, 10, -5, 22, 1, 27, 25, 30};
  int i, j, tmp;
 
   //display the array elements
   for (i=0; i < SIZE; ++i)
   {
      printf("%4d", arr[i]);
   }
 
  for (i=1 ; i <= SIZE-1; i++) {
    j = i;
 
    while (j > 0 && arr[j-1] > arr[j]) {
      tmp = arr[j];
      arr[j] = arr[j-1];
      arr[j-1] = tmp;
 
      j--;
    }
  }
 
  printf("\n******* Array Sorted in Ascending Order *******\n");
 
  for (i=0; i < SIZE; i++)
     printf("%4d", arr[i]);
 
  return 0;
}

Output:

   3  -2   7  10  -5  22   1  27  25  30
******** Array Sorted in Ascending Orde ********
  -5  -2   1   3   7  10  22  25  27  30
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *