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