Algorithms: insertion sort (C language and JavaScript language)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/kuokuo666/article/details/93907739

Insertion Sort of

Code for one-dimensional array of insertion sort

The basic insertion sort operation is to be inserted into a data already sorted ordered data to obtain a new, plus a number of sequenced data, sorting algorithm is suitable for a small amount of data, is stable sorting method.

The basic idea is: n elements to be seen as sort of a table and ordered an unordered list. Start ordered list contains only one element, unordered list contains the n-1 element, each element taken from the first unordered list, it is inserted into the corresponding location in the ordered list, so repeating the sorting process to be completed.

C language

#include <stdio.h>
#include <time.h>

void visitArray(int array[])
{
	int i;
	for (i = 0; i < 20; i++) {
		printf("%d ", array[i]);
	}
	printf("\n");
}

int main()
{
	int array[20] = { 20, 7, 1, 12, 6, 9, 26, 33, 13, 47 , 88, 17, 1, 12, 6, 9, 26, 63, 72, 47};
	printf("排序前的数组:\n");
	visitArray(array);
	int i, j, k;
	for (i = 1; i < 20; i++) {
		for (j = i - 1; j >= 0; j--) {
			if (array[j] < array[i]) {
				break;
			}
		}
		// 找到位置
		if (j != i - 1) {
			// 数据向后移
			int temp = array[i];
			for (k = i - 1; k > j; k--) {
				array[k + 1] = array[k];
			}
			array[k + 1] = temp;
		}
	}
	printf("排序后的数组:\n");
	visitArray(array);
	// 防止控制台消失
	getchar();
	return 0;
}

Here Insert Picture Description

JavaScript

function visit (array) {
	var str = "";
    for (var i = 0; i < array.length; i++) {
	    str += array[i] + " ";
    }
    console.log(str);
}

var array = [20, 7, 1, 12, 6, 9, 26, 33, 13, 47 , 88, 17, 1, 12, 6, 9, 26, 63, 72, 47];
console.log("排序前的数组:");
visit(array);
for (let i = 1; i < array.length; i++) {
    let j;
    for (j = i - 1; j >= 0; j--) {
        if (array[j] < array[i]) {
            break;
        }
    }
    // 找到位置
    if (j != i - 1) {
    // 数据向后移
        let temp = array[i];
        let k;
        for (k = i - 1; k > j; k--) {
            array[k + 1] = array[k];
        }
        array[k + 1] = temp;
    }
}
console.log("排序后的数组:");
visit(array);

Here Insert Picture Description

O (∩_∩) O ~~

Guess you like

Origin blog.csdn.net/kuokuo666/article/details/93907739