Skip to content

Commit 128d3a4

Browse files
committed
code modified a bit
1 parent f381e80 commit 128d3a4

File tree

1 file changed

+7
-14
lines changed

1 file changed

+7
-14
lines changed

insertion_sort/insertion_sort.cpp

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,18 @@
11
#include <bits/stdc++.h>
22
using namespace std;
3-
43
void insertionSort(int array[], int size)
54
{
6-
int i = 0, j = 0, tempElement = 0, tempIndex = 0, flag = 0;
5+
int i = 0, tempElement = 0, j = 0;
76
for (i = 1; i < size; i++)
87
{
9-
tempElement = array[i]; //taking an array element into tempElement
10-
for (j = i - 1; j >= 0; j--)
8+
tempElement = array[i]; //Choosing element whose correct index to be found.
9+
j = i - 1;
10+
while (j >= 0 && array[j] > tempElement)
1111
{
12-
if (array[j] > tempElement)
13-
array[j + 1] = array[j];
14-
else
15-
flag = 1; //checking if we got the correct position of tempElement
16-
break;
17-
}
18-
if (flag == 1 || j == -1) //condition checking if we got correct position of tempElement or not
19-
{
20-
flag = 0;
21-
array[j + 1] = tempElement; //putting tempElement to it correct position
12+
array[j + 1] = array[j]; //Shifting element one position right side untill we get correct position
13+
j = j - 1;
2214
}
15+
array[j + 1] = tempElement; // got the correct position for tempElement
2316
}
2417
}
2518
void display(int array[], int size)

0 commit comments

Comments
 (0)