您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】直接插入排序

2015-12-31 20:29 357 查看
头文件:

#include <iostream>
using namespace std;

#define MAX 10

typedef struct
{
int r[MAX];
}Sqlist;

// 交换两个数
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
return;
}

// 比較大小
void InsertSort(Sqlist &sl, int n)
{
for (int i = 1; i<6; ++i)
{
if (sl.r[i] < sl.r[i - 1])
{
for (int j = i; j>0 && sl.r[j] < sl.r[j - 1]; --j)
{
swap(sl.r[j], sl.r[j - 1]);
}
}
}
}


主函数:

#include "InsertSort.h"

int main()
{
Sqlist sq = { 21, 25, 49, 25, 16, 8 };
InsertSort(sq,6);
for (int i = 0; i < 6; ++i)
{
cout << sq.r[i] << " ";
}
cout << endl;
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: