# Insertion Sort - Part 2

# Insertion Sort - Part 2

cdima + 7 comments Pretty badly described algorithm, needs a better description of the steps.

lk00100100 + 0 comments [deleted]lk00100100 + 11 comments You can sort of follow this GIFFY

https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif

krishna3317 + 0 comments Thanks it helped me

surya_palla1 + 0 comments thank u , it helped me.

dlgustlr45 + 0 comments Thank you very much!!

Lundii + 0 comments Thanks. Very helpful.

mohansai01234 + 0 comments thanks bro. it helped me a lot

wqian + 0 comments Thank you! It helped me!

arpit_vaish89 + 0 comments Thank you , helped a lot!

adamxtokyo + 0 comments Thanks, that helped a lot. Here's my Javascript implementation of that gif lol =P

function insertionSort2 (n, arr) { let storage for (let i = 1; i < n; i++) { storage = arr.splice(i, 1)[0] for (let j = i; j >= 0; j--) { if (storage > arr[j-1] || j === 0) { arr.splice(j, 0, storage) break } } console.log(arr.join(' ')) } }

yaroverg + 0 comments The GIFY was great

yashdeepagarwal + 0 comments Thank you. Helped alot!

akshay_goyal1008 + 0 comments thanks for the giffy

sshivasurya + 1 comment https://github.com/shivasurya/cc150/blob/master/sorting/insertions%20sort/C%20lang/insertion.c

check this with algorithm description

wqian + 0 comments Wow, thank you for sharing! It helped me!

duniya_ke_neta + 1 comment [deleted]alison_thaung + 1 comment Here's another, slightly condensed Python3 solution

s = int(input().strip()) ar = [int(temp) for temp in input().strip().split(' ')] def insertionSort(ar, i): new = sorted(ar[:i+1]) + ar[i+1:] return ' '.join(str(k) for k in new) for i in range(1, s): print(insertionSort(ar, i))

kerryjones21 + 0 comments Using an in-built sort function defeats the purpose of learning sorting algorithms...

formiaczek + 3 comments agreed, it's a shame that it assumes some iterations that print the array even if nothing was moved, i.e.:

Input 6 1 4 3 5 6 2 Expected Output 1 4 3 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6

And solutions like:

void insertion_sort(vector<int> values) { print_values(values); while(true) { auto what = std::adjacent_find(values.begin(), values.end(), std::greater<int>()); if(what == values.end()) { return; } auto last = what+1; auto v = *last; auto tmp = *last; auto where = std::lower_bound(values.begin(), what, v); for(auto x = last; x != where; --x) { auto prev = x-1; *x = *prev; } *where = tmp; print_values(values); } }

that are insertion sort, would print it only when it actually changed, i.e.:

Your Output (stdout) 1 4 3 5 6 2 1 3 4 5 6 2 1 2 3 4 5 6

BALYAM_muralidh2 + 1 comment static void insertionSort2(int n, int[] arr) { // Complete this function for(int k=0;k<arr.length-1;k++){ for(int i=0;i<arr.length-1;i++){ int key = arr[k+1]; if(i==k+1) break; if(arr[i]>key){ arr[k+1]=arr[i]; arr[i]=key; } } for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+" "); } System.out.println(); } }

pheonixevolution + 0 comments thanks it helped me !

atript + 0 comments i think the idea is that they can check whether you have implemented the algorithm right. that is more accurately tested when all iterations and exchanges are recorded.This is not about efficiency, its about learning.

facitoo + 0 comments dude! thats heck of a complex solution!

billchenxi + 0 comments I agreed, why do we have to print out in that weird way???

darmuneeb322 + 0 comments The problem seems to be designed in a very bad way.But after finally solving it you kindof get the idea what insertion sort does at every step.

Octowl + 5 comments For those trying this in javaScript, remember that the input is an array of strings.

You need to map the elements to integers using:

`arr.map(function(x) { return parseInt(x, 10); });`

mohhasbias + 0 comments Thank you. that's exactly what i need to fix my submission. my solution was string based sorting.

hdennen + 0 comments arr.map(Number) works just as well. Still, this was my bug so good spot.

dtudury + 0 comments exactly this, saved me some frustration, thank you!

`arr.map(Number)`

or`arr.map(x => +x)`

are cuter though :)Drakontium + 0 comments [deleted]gksander93 + 0 comments Life saver.

vshantam + 7 comments Python 3 b=int(input()) a=[int(x) for x in input().strip().split(' ')] for i in range(1,len(a)): key=a[i] j=i-1 while j>=0 and a[j]>key: a[j+1]=a[j] j=j-1 a[j+1]=key print(*a)

Do let me know if there is more finer solution in python.

runcy + 1 comment loved the usage of *a. Learnt something new instead of using join()

SebastianNielsen + 2 comments You can't use join, the list doesn't contain strings but integers.

15533_mohanvamsi + 1 comment you can use join...

print(' '.join(str(i) for i in array))

davebrophy + 0 comments or

print(' '.join(map(str,array)))

vshantam + 0 comments it can be used because python provides str() functions which can convert interger to strings

vshantam + 1 comment I am glad you learned something new..Do let me know if i can help you with something.

runcy + 1 comment Awesome! and thanks for the help offered. What would be in your opinion are good resources to learn advanced python concepts and also get better at Data Structures and Algorithms?

vshantam + 1 comment In case of Algorithms and Data structures I would reccomend you to learn from "CLRS" and even i do the same its a very good book. In case of Advanced Python i suggest you to join online courses because it's a language the more you do the more you learn.

runcy + 0 comments Cool. Thanks! I seem to be on the right path then

[deleted] + 0 comments Insertion swapping

GeoMatt22 + 1 comment I did about the same, but using a sentinel at the front of the array:

n, amin = int(input()), -10**4 A = [2*amin] + list(map(int, input().split())) for j in range(2, n+1): i, a = j, A[j] while a < A[i-1]: A[i] = A[i-1] i -= 1 A[i] = a print(*A[1:])

vshantam + 0 comments Thanks,learned something new.

lan956 + 1 comment def insertion_sort(ar):

`for i in range(1, len(ar)): for j in range(i): if (ar[i]<ar[j]): k = ar[i] ar[i] = ar[j] ar[j] = k print(*ar)`

ace_dexter + 0 comments I think its bubble sort!

lan956 + 0 comments [deleted]Ramya_Vadigineni + 0 comments [deleted]

briancmpbll + 2 comments In the C++ code, why switch from vectors in Part 1 to C arrays in Part 2??

peterkirby + 1 comment [deleted]foxeed + 1 comment You missed the point of these challenges with this cheesy std::sort(). >:(

peterkirby + 0 comments That wasn't my intention at all. I was offering a possible explanation for the switch to C arrays, which was the question. Apparently I was misunderstood (practically in the opposite sense - I was suggesting we were to avoid using conveniences of the STL), so I removed it.

NiceBuddy + 0 comments @briancmpbll did you get the answer for this?

RodneyShag + 3 comments ### Java solution - passes 100% of test cases

public static void insertionSortPart2(int[] array) { for (int i = 1; i < array.length; i++) { int j = i; int value = array[i]; while (j >= 1 && array[j-1] > value) { array[j] = array[j-1]; j--; } array[j] = value; printArray(array); } }

Full solution available in my HackerRank solutions.

Let me know if you have any questions.

adamchenwei + 1 comment Hey, converted your answer to JS, but it will only pass first 2 test, thought?

for (var i = 1; i < array.length; i++) { var j = i; var value = array[i]; while (j >= 1 && (array[j-1] > value)) { array[j] = array[j-1]; j--; } array[j] = value; console.log(array.join(' ')); }

RodneyShag + 1 comment Looks identical. My full solution also prints a newline after each array. My best guess is to make sure the output looks like the expected output in the testcase.

tawriffic + 1 comment It might be sorting the numbers 'alphabetically' instead of 'numerically'....my JS code only passed the first two tests until I realised this. Need the array contents to be integers not string characters. So my array was looking like 2,20,23,26,3,4,5,52, 6 etc

RodneyShag + 0 comments Nice find!

Vasu1819 + 1 comment Hi, I've written a similar code but it failed 3/5 test cases reason being error with ArrayOutOfBound exception. Can you please tell me what wrong did I do? Thanks.

for(int j=1;j<ar.length;j++){ int temp=ar[j]; int k = j-1; while(ar[k]>temp&&k>=0) { ar[k+1]=ar[k]; k--; } ar[k+1]=temp; printArray(ar); }

RodneyShag + 1 comment What's the input of the test case that's failing?

Vasu1819 + 1 comment Test cases 1,2and4. Input of test case 1 being: 9 9 8 6 7 3 5 4 1 2

RodneyShag + 2 comments Hi. The problem is with this line of your code:

while(ar[k]>temp&&k>=0)

It evaluates the expression inside the () from left to right. So it first tries to do ar[k], where k is -1 and it gets an Index Out of Bounds Exception. To fix it, you can change it to

while(k >= 0 && ar[k] > temp)

Now, it will check for k >= 0 first. If it's not greater than 0, the next expression (to the right of &&) will not evaluate.

This is called short circuit evaluation

Vasu1819 + 0 comments Man you are awesome. You made my day. I didn't know about this, thank you. Thank you so much :-)

tripathi_shubha1 + 0 comments thanku so much !!

RA1511003010711 + 1 comment is there any need to use "value"..? Can't we simply write array[j-1]>array[i] ..?

RodneyShag + 0 comments You need to save array[i], since the while loop will be overwriting it.

rabbitfighter + 1 comment The JavaScript solutions are wrong, again. This is the third one I've found where the test cases are wrong. :(

ggorlen + 0 comments They seem to be working now.

function processData(input) { let arr = input.split("\n")[1].split(' ').map(Number); for (let i = 1, j = i; i < arr.length; j = ++i) { while (arr[j] < arr[j-1] && j) { let temp = arr[j-1]; arr[j-1] = arr[j]; arr[j--] = temp; } console.log(arr.join(' ')); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });

gursimran16 + 1 comment #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, x; cin >> n; vector <int> a; for(int i = 0; i < n; i++){ cin >> x; a.push_back(x); } for(int i = 1; i < n; i++){ int j = i - 1; while(a[j] > a[j+1]){ int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; j--; } for(int i = 0; i < n; i++){ cout << a[i] << " "; } cout << endl; } return 0; }

b0kater + 0 comments No, you are not supposed to put the element into the sorted array until you find its final position.

Originally linked by someone else: https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif

marcos_sb + 4 comments Do not

*printf*in Java 8 or you will timeout...evancrutcher + 0 comments Thanks for this tip! Fixed my timeouts.

off99555 + 0 comments Try using BufferedWriter.

kangkanlahkar1 + 1 comment One can try this to print the entire array in a single line code.....

**System.out.println(Arrays.toString(ar).replace("[","").replace("]","").replace(",",""));**Balwinder1012 + 0 comments Thanks for tip

vldvel + 0 comments Simple JavaScript solution

arr.reduce((p,c,i) => { if (i === 0) return p; if (c < p.curr[i - 1]) { p.curr.splice(i, 1); p.curr.splice(p.curr.findIndex((e) => e > c), 0, c); } p.answer.push(p.curr.join(' ')); return p; }, {curr: [...arr], answer: []}).answer.join('\n');

pratheep_my + 0 comments Javascript solution;

for (let i = 1; i < n; i++) { for (let j = 0; j < i; j++) { if (arr[j] > arr[i]) { const temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } process.stdout.write(arr.join(' ') + '\n'); }

Sort 270 Discussions, By:

Please Login in order to post a comment