0% found this document useful (0 votes)
5 views3 pages

Downloadfile 4

Uploaded by

gargabhinav1507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Downloadfile 4

Uploaded by

gargabhinav1507
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Abhinav 11232510 4A1

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>

void insertionSort(int arr[], int N) {


// Start from the second element
for (int i = 1; i < N; i++) {
int key = arr[i];
int j = i - 1;

// 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;

BSCE-508L DESIGN AND ANALYSIS OF ALGORITHM 1


Abhinav 11232510 4A1

}
}

void printArray(int arr[], int N) {


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

int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);

int arr[n]; // Declare the array with user-defined size

// Input elements in the array


printf("Enter elements in the array: \n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Sort the array using insertion sort


insertionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);

return 0;
}

BSCE-508L DESIGN AND ANALYSIS OF ALGORITHM 2


Abhinav 11232510 4A1

Output:
1. Best case:

TIME COMPLEXITY: O(n)


2. Average case:

TIME COMPLEXITY: O(n2)

3. Worst case:

TIME COMPLEXITY: O(n2)

BSCE-508L DESIGN AND ANALYSIS OF ALGORITHM 3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy