Insertion Sort

Problem

Write a program that sorts in ascending order when N numbers are input and outputs them.
The sorting method is insertion sort.

input

  • The first line is given a natural number N (1<=N<=100).
  • In the second line, N natural numbers are entered with a space between them. Each natural number is in the range of integers.
6

11 7 5 6 10 9

output

Prints a sequence sorted in ascending order.

5 6 7 9 10 11

Solution

function solution(arr) {
	let answer = arr;

	for (let i = 0; i < arr.length; i++) {
		let tmp = arr[i],
			j;

		for (j = i - 1; j >= 0; j--) {
			console.log(arr);
			if (arr[j] > tmp) arr[j + 1] = arr[j];
			else break;
		}

		arr[j + 1] = tmp;
	}

	return answer;
}