// select sort.cpp : Defines the entry point for the console application.
/*
* 1 随机生成数列 srand(unsigned (time(0))), rand()
* 2 insert sort
* 3 insert_sort(int s[],)参数int s[] 等价于 int * const s;
*/
#include "stdafx.h"
#include <iostream>
#include <ctime> //time()
#include <cstdlib> //srand(),rand()
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
void insert_sort(int * const, int);
const int length = 10;
int s[length];
srand(unsigned (time(0))); //用时间种子初始化随机数发生器
for(int i =0; i < length; i ++)
{
s[i] = rand()%10;
cout << "s[" << i <<"] = " << s[i] <<endl;
}
//insert sort****
insert_sort(s,length);
cout << "=============\ninsert sort" << endl;
for(int i = 0; i < length; i++) cout << "s[" << i <<"] = " << s[i] <<endl;
system("pause");
return 0;
}
void insert_sort(int * const s, int length)
{
//从第二个元素开始排序,和之前的元素不断比较,交换,插入。
for(int j = 1; j < length; j++)
{
int key = s[j];
int i;
for(i = j-1; i >= 0 && s[i] > key; s[i+1] = s[i--]); //i--
s[i+1] = key;
}
}
/*
* 1 随机生成数列 srand(unsigned (time(0))), rand()
* 2 insert sort
* 3 insert_sort(int s[],)参数int s[] 等价于 int * const s;
*/
#include "stdafx.h"
#include <iostream>
#include <ctime> //time()
#include <cstdlib> //srand(),rand()
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
void insert_sort(int * const, int);
const int length = 10;
int s[length];
srand(unsigned (time(0))); //用时间种子初始化随机数发生器
for(int i =0; i < length; i ++)
{
s[i] = rand()%10;
cout << "s[" << i <<"] = " << s[i] <<endl;
}
//insert sort****
insert_sort(s,length);
cout << "=============\ninsert sort" << endl;
for(int i = 0; i < length; i++) cout << "s[" << i <<"] = " << s[i] <<endl;
system("pause");
return 0;
}
void insert_sort(int * const s, int length)
{
//从第二个元素开始排序,和之前的元素不断比较,交换,插入。
for(int j = 1; j < length; j++)
{
int key = s[j];
int i;
for(i = j-1; i >= 0 && s[i] > key; s[i+1] = s[i--]); //i--
s[i+1] = key;
}
}
本文通过C++代码演示了插入排序的基本实现过程。首先使用srand()和rand()生成了一个包含10个随机整数的数组,并打印了初始数组。然后定义了一个插入排序函数,实现了排序逻辑并打印了排序后的数组。
2967

被折叠的 条评论
为什么被折叠?



