insertion sort - part 1 hackerrank solution python code example
Example 1: insertion sort python
def insertionSort(alist):
for i in range(1,len(alist)):
#element to be compared
current = alist[i]
#comparing the current element with the sorted portion and swapping
while i>0 and alist[i-1]>current:
alist[i] = alist[i-1]
i = i-1
alist[i] = current
#print(alist)
return alist
print(insertionSort([5,2,1,9,0,4,6]))
Example 2: insertion sort python
def insertion_sort(lst):
for i in range(1,len(lst)):
while i > 0 and lst[i - 1] >lst[i] :
lst[i - 1], lst[i] = lst[i] , lst[i - 1]
## swapping
i = i -1
return lst
print(insertion_sort([4,2,2,3,4,3,1,1,1,2]))
Example 3: insertion sort part 1 hackerrank solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>
void print(int ar_size, int *ar)
{
for (int i = 0; i< ar_size; i++)
{
printf("%d ", ar[i]);
}
printf("\n");
}
void insertionSort(int ar_size, int * ar)
{
int small, sorted = 1, position;
for (int i = 0; i< ar_size; i++)
{
if (ar[i] > ar[i+1])
{
small = ar[i+1];
position = i;
break;
}
}
while (sorted != 0)
{
ar[position + 1] = ar[position];
print(ar_size, ar);
if (small < ar[position - 1])
{
position--;
continue;
}
ar[position] = small;
print(ar_size, ar);
sorted = 0;
}
}
int main(void) {
int _ar_size;
scanf("%d", &_ar_size);
int _ar[_ar_size], _ar_i;
for(_ar_i = 0; _ar_i < _ar_size; _ar_i++) {
scanf("%d", &_ar[_ar_i]);
}
insertionSort(_ar_size, _ar);
return 0;
}