c语言插入排序算法_插入排序算法,流程图和C,C ++代码

本文介绍了插入排序的基本原理,它通过选取关键元素并将其插入到正确位置来进行排序。文章提供了排序过程的逻辑解释,并提及在排序开始时,关键元素通常是第二个元素。对于升序或降序排序,关键元素会根据需要与左侧元素交换位置。为了深入理解,文章还给出了插入排序的算法逻辑。
摘要由CSDN通过智能技术生成

c语言插入排序算法

In the last article, we discussed about the bubble sort with algorithm, flowchart and code. In this article, we are going to discuss about another basic sorting technique i.e. insertion sort.

在上一篇文章中,我们讨论了用算法,流程图和代码进行冒泡排序 。 在本文中,我们将讨论另一种基本的排序技术,即插入排序

As the name suggests the sorting is done by using successive insertions of the key element selected by the sorting algorithm at its correct place. As the sorting begins the key element chosen is always the second element so that there can be at least one element at the left of the key element to be compared. After comparison the key element is swapped with the element at its left if required and the key element is changed to the element at the immediate right of the previous key element after that the key element is again compared with the elements at it left and the element is swapped with the key element after comparison if required, if the sorting is done in ascending order then the key element should always be greater than the element at its left if not, then the swapping is performed with key element and vice versa for the descending order.

顾名思义,排序是通过在正确的位置使用由排序算法选择的关键元素的连续插入来完成的。 在排序开始时,所选的关键元素始终是第二个元素,以便在要比较的关键元素的左侧至少可以有一个元素。 比较之后,如果需要,将关键元素与其左侧的元素交换,然后将关键元素更改为上一个关键元素的紧邻右侧的元素,之后再次将关键元素与其左侧的元素和该元素进行比较如果需要,则在比较后与key元素交换,如果排序以升序进行,则key元素应始终大于其左侧的元素(如果不是),则对key元素进行交换,反之亦然订购。

Let us look at the algorithm of insertion sort for a better understanding of the logic to be used:

让我们看一下插入排序算法,以更好地了解要使用的逻辑:

    Insertion sort(a[],n)
    for j->2 to n
        do key =0 and a[i]>key
            do a[i+1]

The algorithm can also be explained in the form of a flowchart as follows:



C code for Insertion sort

#include<stdio.h>

int main()
{
    
	int a[6];
	int key;
	int i,j;
	int temp;

	printf("Enter any six elements to be sorted using insertion sort\n");
	for(i=0;i<6;i++)
	{
    
		scanf("%d",&a[i]);
	}

	for(j=1;j<6;j++)
	{
    
		key=a[j];
		i=j-1;
		while((i>=0)&&(a[i]>=key))
		{
    
			temp=a[i+1];
			a[i+1]=a[i];
			a[i]=temp;
			i=i-1;
		}
		a[i+1]=key
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值