C ++直接插入排序算法

直接插入排序的原理:将一个待排序的元素,通过与前面已经排好序的有序序列所有元素进行比较后,再插入到有序序列中。

#include <iostream>
#include <stdlib.h>
using namespace std;

/*****************************************************************/
/*  插入排序
/****************************************************************/

void swap( int array[], int j)  //位置互换函数
{
	int temp = array[j];
	array[j] = array[j-1];
	array[j-1] = temp;
}


void InsertSort(int array[], int n)  //插入排序函数
{
	for (int i = 1; i < n; i++)  //当i小于n则结束循环
	
		for ( int j = i; j > 0; j--)  //j--是有序数组从尾到头进行比较
		{
			if(array[j] < array[j-1])  
			swap(array[j], array[j-1]);  //如果条件成立,就调用swap函数进行位置互换
			else
				break;    //如果条件不成立,就结束本次循环
		}
	}
}


int main(void)  //主程序
{
	
	const int n = 6;  //数组元素的数量
	cout << "请输入6个整数: " << endl;
	int array[n];
	for (int i = 0; i < n; i++)  
	{
		cin >> array[i];
	}
	

	InsertSort(array, n);  //调用InsertSort函数,进行比较

	cout << endl;  //换行

	cout << "由小到大的顺序排列后: " << endl;
	for (int i = 0; i < 6; i++)  
	{
		cout << array[i] << ",";  
	}

	cout << endl << endl;  //换行

	system("pause");  //调试时,黑窗口不会闪退,一直保持
	return 0;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/xinxudongstudy/article/details/82626241