Skip to content

Commit 57bd9c0

Browse files
added insertion sort algo
1 parent 9e7aa43 commit 57bd9c0

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Sorting Algorithms/insertion_sort.cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Bubble sort
2+
// Bubble sort is Adaptive and Stable sort
3+
// the lightest elements bubbles up and heavier gets settled down
4+
5+
#include <iostream>
6+
using namespace std;
7+
8+
void Swap(int &x, int &y)
9+
{
10+
int temp = x;
11+
x = y;
12+
y = temp;
13+
}
14+
15+
void InsertionSort(int Arr[], int size)
16+
{
17+
int i, j, x;
18+
for (i = 1; i < size; i++)
19+
{
20+
j = i - 1;
21+
x = Arr[i];
22+
while (j > -1 && Arr[j] > x)
23+
{
24+
Arr[j + 1] = Arr[j];
25+
j--;
26+
}
27+
Arr[j + 1] = x;
28+
}
29+
}
30+
31+
void Display(int Arr[], int size)
32+
{
33+
for (int i = 0; i < size; i++)
34+
cout << Arr[i] << " ";
35+
}
36+
int main()
37+
{
38+
int Arr[] = {3, 6, 4, 9, 2, 8, 12, 10};
39+
int size = sizeof(Arr) / sizeof(Arr[0]);
40+
41+
InsertionSort(Arr, size);
42+
Display(Arr, size);
43+
44+
return 0;
45+
}
46+
47+
// Analysis :
48+
49+
// Time :
50+
// Pass : n - 1
51+
// max no. of Swaps 1 + 2 + 3 + ... + n - 1 = O(n^2)
52+
// no. of Comparison 1 + 2 + 3 + ... + n - 1 = O(n^2)
53+
// O(n^2), Quadratic
54+
55+
// Splace : O(1), Constant

0 commit comments

Comments
 (0)