Downloadfile 4
Downloadfile 4
Practical no. 1
Aim: Implementation of Insertion Sorting technique using Incremental
approach.
Theory: Insertion sort is a simple sorting algorithm that works by iteratively
inserting each element of an unsorted list into its correct position in a sorted
portion of the list.
Algorithm:
Step 1. Input the desired number of elements in array A [ ].
Step 2. FOR j ← 2 TO length [A] DO step 3 to 6.
Step 3. key ← A [j] {Put A [j] into the already sorted sequence A [1 . . j − 1]}
Step 4. i ← j − 1
Step 5. WHILE i > 0 and A [i] > key DO A [i +1] ← A [i] and set i ← i – 1.
Step 6. Set A [i + 1] ← key.
Step 7. Print sorted array A [ ].
Program Code:
#include <stdio.h>
// Move elements of arr[0..i-1], that are greater than key to one position to the right
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Move the key to its correct position
arr[j + 1] = key;
}
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
return 0;
}
Output:
1. Best case:
3. Worst case: