前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Insertion Sort

Insertion Sort

作者头像
废江_小江
发布2022-09-05 13:18:44
2410
发布2022-09-05 13:18:44
举报
文章被收录于专栏:总栏目

Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

代码语言:javascript
复制
for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key

Note that, indices for array elements are based on 0-origin.

To illustrate the algorithms, your program should trace intermediate result for each step.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by a single space.

Output

The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6

5 2 4 6 1 3

Sample Output 1

5 2 4 6 1 3

2 5 4 6 1 3

2 4 5 6 1 3

2 4 5 6 1 3

1 2 4 5 6 3

1 2 3 4 5 6

Sample Input 2

3

1 2 3

Sample Output 2

1 2 3

1 2 3

1 2 3

Hint

Template in C

Meaning

实现插入排序的过程

Solution

插入排序第二层循环中是从当前处(也是未排序的这个数)向前寻找比其大的数,如果有向后移动一位。临界条件两个,1,不能再向前了(判断此刻指针下标大于0)2,有比其更小的数(判断指针是否比当前处的数小)。最后将当前数插入到指针的位置

Coding

代码语言:javascript
复制
#include<iostream>
using namespace std;
void print(int a[], int n) {
	int i;
	for (i = 0; i < n; i++) {
		if (i > 0) cout<<" ";
		cout << a[i];
	}
	cout << endl;
}
void insertionsort(int a[], int n) {
		int i, j, tmp;
		for (i = 1; i < n; i++) {
			tmp = a[i];
			for (j = i; j > 0 && a[j - 1] > tmp; j--) 
				a[j] = a[j - 1];
				a[j] = tmp;
			print(a, n);
		}
	}
int main() {
	int n;
	int a_list[105];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a_list[i];
	}
	print(a_list, n);
	insertionsort(a_list, n);
}

废江博客 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权

转载请注明原文链接:Insertion Sor

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-03-28),如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Meaning
  • Solution
  • Coding
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档