forked from ankit-kaushal/Lets-go-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.cpp
More file actions
65 lines (61 loc) · 988 Bytes
/
InsertionSort.cpp
File metadata and controls
65 lines (61 loc) · 988 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void insertion_sort(int *arr, int from, int to)
{
int key = 0;
int j = 0;
for(int i = from + 1; i <= to; i++)
{
key = arr[i];
j = i - 1;
while(key < arr[j] && j >= from)
{
arr[j + 1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
void doiSort(int buf[], int len, int maxl)
{
if (len >= maxl)
{
return;
}
if (len == 1)
{
if (buf[0] > buf[1])
{
//cout << " Shift 1" << endl;
int r = buf[1];
buf[1] = buf[0];
buf[0] = r;
}
doiSort(buf, 2, maxl);
}
else
{
int m = buf[len];
for (int i = 0; i < len; i++)
{
if (buf[i] > m)
{
//cout << "insert " << buf[i] << "->" << buf[len] << " " << endl;
for (int j = len; j > i; j--)
{
int t = buf[j];
buf[j] = buf[j - 1];
buf[j - 1] = t;
}
break;
}
}
doiSort(buf, len + 1, maxl);
}
return;
}