直接插入排序学习笔记与学习心得

直接插入排序学习笔记与学习心得

插入排序代码

编写环境Xcode 使用语言C++

//
//  main.cpp
//  直接插入排序
//
//  Created by Neil Xie on 2020/3/23.
//  Copyright © 2020 Neil Xie. All rights reserved.
//

#include 
 
using namespace std;
 
void print(int a[], int n ){
    cout<

代码运行结果如下:

9:1 3 5 7 2 4 9 6 6 
9:1 3 5 7 2 4 9 6 6 
9:1 3 5 7 2 4 9 6 6 
9:1 2 3 5 7 4 9 6 6 
9:1 2 3 4 5 7 9 6 6 
9:1 2 3 4 5 7 9 6 6 
9:1 2 3 4 5 6 7 9 6 
9:1 2 3 4 5 6 6 7 9 
9:1 2 3 4 5 6 6 7 9 
Program ended with exit code: 0

直接插入排序的步骤:

1、建立一个哨兵(即临时变量),将要插入的数据(即要排序的数据)赋给这个临时变量。

2、插入数据从后面开始比较,如果大于前面,就记录下标,并将数据后移,直到插入数据碰到比他小的。

3、将临时变量赋值给当前记录下标。

4、用循环语句完成全部数据的插入。

代码的部分解读

void print(int a[], int n ){
    cout<

定义了一个函数:

​ 作用是每次排序之后,都将本次排序后的结果打印出来,使排序的过程清晰明了。


void InsertSort(int a[], int n)
{
    for(int i= 1; i

这个部分是直接插入排序的核心内容:

​ 1、首先使用循环,将需要排序的数值全部过一遍。

​ 2、使用比较语句,从最后开始排序,如果前面的数小于标兵中的数,则直接插入;如果前面的数大于标兵中的数,则记录其下标,并将其后移一位。

​ 3、打印每次排序的结果。

其他插入排序的做法

代码如下:

#include
#include
 
using namespace std;
 
//交换数组元素位置位置
void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}
 
 
/*
插入排序。注意,若后面一个元素比其前面一个元素小,则将这两个元素交换位置,然后再来比较这个插入元素与前面一个元素的大小,若小,则还需要交换这两个元素位置,一直到这个插入元素在正确的位置为止
*/
void insertSort(int a[],  int length)
{
	for (int i = 1; i < length; i++)
	{
		for (int j = i - 1; j >= 0 && a[j + 1] < a[j]; j--)
		{
			swap(a[j], a[j + 1]);
		}
	}
 
}
 
int main()
{
	int a[] = { 2,1,4,5,3,8,7,9,0,6 };
 
	insertSort(a, 10);
 
	for (int i = 0; i < 10; i++)
	{
		cout << a[i] << "";
 
	}
	cout << endl;
	system("pause");
	return 0;
 
}

代码核心思想:

使用一个交换前后顺序的函数,在一个数组中,重复使用该函数多次,直至完成排序。

你可能感兴趣的:(直接插入排序学习笔记与学习心得)