// 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;
}
}