排序之直接插入排序(C++)

直接排序就是将未排序部分的元素插入到已排序的元素列表中,代码实现:

Input number (q to quite): 9 6 4 1 3 9 4 6 8 7 3 1 6 4 5 9 4 q
Your input List is: 9 6 4 1 3 9 4 6 8 7 3 1 6 4 5 9 4
After sort: 1 1 3 3 4 4 4 4 5 6 6 6 7 8 9 9 9
#include<iostream>

using namespace std;

#define MAXSIZE 100

struct List
{
	int data[MAXSIZE];
	int size;
};

void swap(List &L, int i, int j)
{
	int temp = L.data[i];
	L.data[i] = L.data[j];
	L.data[j] = temp;
}

void show(const List &L)
{
	for (int i = 0; i < L.size; i++)
		cout << L.data[i] << " ";
	cout << endl;
}

void InsertSort(List &L)
{
	for (int i = 1; i < L.size; i++) {
		int temp = L.data[i];
		int j = i - 1;
		while (j >= 0 && temp < L.data[j]) {
			L.data[j + 1] = L.data[j];
			j--;
		}
		L.data[j + 1] = temp;
	}
}

void main()
{
	List test;
	cout << "Input number (q to quite): ";
	int temp;
	test.size = 0;
	while (test.size <= MAXSIZE&&cin >> temp) {
		test.data[test.size] = temp;
		test.size += 1;
		//cout << "Input number (q to quite): ";
	}
	cin.clear();
	cin.ignore(100, '\n');
	cout << "Your input List is: ";
	show(test);
	cout << "After sort: ";
	InsertSort(test);
	show(test);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值