Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
44 views9 pages

Insertion Sortingtrh

The document covers the insertion sorting algorithm, which sorts an array by building the final sorted array one element at a time. It explains the procedure with an example and discusses the time complexity, stating that the average and worst-case time complexity is O(n). Additionally, it includes a code snippet in C++ demonstrating the implementation of insertion sort.

Uploaded by

extraclassdaily
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)
44 views9 pages

Insertion Sortingtrh

The document covers the insertion sorting algorithm, which sorts an array by building the final sorted array one element at a time. It explains the procedure with an example and discusses the time complexity, stating that the average and worst-case time complexity is O(n). Additionally, it includes a code snippet in C++ demonstrating the implementation of insertion sort.

Uploaded by

extraclassdaily
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/ 9

DSA SERIES

- Learn Coding
Topic to be Covered today

Insertion sorting
Lets start today’s Lecture
Insertion sorting
• Simple sorting algorithm
• Builds the final sorted array one element at a time.
• It takes each element and inserts it into its correct position in the
sorted part of the array.

Repeat the process until the array is sorted.


Procedure :
Example :
[5 4 3 2 1 ] [2 3 4 5 1 ]
[2 3 4 1 5 ]
[2 3 1 4 5 ]
[5 4 3 2 1 ]
[2 1 3 4 5 ]
[4 5 3 2 1 ]
[1 2 3 4 5 ]

[4 5 3 2 1 ]
[4 3 5 2 1 ]
[3 4 5 2 1 ]

[3 4 5 2 1 ]
[3 4 2 5 1 ]
[3 2 4 5 1 ]
[2 3 4 5 1 ]
Time Complexity
1st -- 1 comparision
2nd --- 2 comparision

n ---- n-1 comparision

2
T.C = O( n ) -> Average and Worst case

Best case – O(n)


Learn coding

Thank you
Code :
#include <iostream>
using namespace std;

int main()
{
// int arr[]= {9,-1,2,8,3,7,6,11,-4};

int arr[]= {1,1,1,1,1,1};

int size = sizeof(arr)/sizeof(arr[0]);

cout<< "Printing the original array :";

for(int i =0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
// logic

for(int i =1;i<size;i++){
int temp = arr[i];
int j = i-1;
for( ;j >= 0;j--){
if(arr[j] >temp ){
arr[j+1]= arr[j];
}
else {
break;
}
}
arr[j+1] = temp ;
}
cout<< "Printing the array after sorting :";
for(int i =0;i<size;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}

You might also like