【数据结构】第八章-插入排序

插入排序属于稳定排序算法

插入排序基本思想:每次将一个待排序的记录按其关键字大小插入前面已排好的子序列,直到全部记录插入完成。

时间复杂度:最好 O(n)、最坏 O(n2)

空间复杂度:O(1)


C++代码实现:

#include<iostream>
using namespace std;
/**
1.插入排序 
**/
void InsertSort(int a[], int n);

int main() {
	int a[]={6,2,9,4,8,5,1};
	InsertSort(a,7); 
	for(int i=0;i<7;i++) {
		cout << a[i];
	}
}

void InsertSort(int a[], int n) {
	int i,j,t;
	for(i=1;i<n;i++) {
		if(a[i]<a[i-1]) {
			t=a[i];
			for(j=i-1;j>=0 && a[j] > t;j--) {
				a[j+1]=a[j];
				a[j]=t;
			}
		} 
	} 
} 

猜你喜欢

转载自blog.csdn.net/m0_53129012/article/details/118255064