C++實現插入排序演算法(個人理解編寫)
阿新 • • 發佈:2021-01-24
原始碼:
#include <iostream>
#include <cstdlib> //rand() 和 srand()的標頭檔案
#include <ctime> //time的標頭檔案
#define MAXSIZE 10 //巨集定義陣列最大容量
using namespace std;
void make_sorted(int * array) //隨機生成100以內的亂序整數
{
srand((unsigned int)time(NULL));
cout << "隨機生成的10個數為:" ;
for(int i = 1; i < MAXSIZE + 1; i++)
{ //這裡把array[0]留著當中轉站用
array[i] = rand() % 100;
cout << array[i] << " ";
}
cout << endl;
}
void insert_sort(int * array) //插入排序
{
for (int i = 1; i < MAXSIZE; i++) //10個數排序需要排9次
{
array[0] = array[i + 1]; //a[i]不動,a[i+1]取出來賦值給a[0]
for(int j = i; j > 0 ; j--) //a[0]和前i個數需要比較i次,比較完插入進去需要移動i個數
{
if (array[0] < array[j] ) //如果a[0]小於a[j]可以理解為找到a[0]的位置了
{
array[j + 1] = array[j];//a[j+1]往後移
array[j] = array[0]; //a[0]放進去
}
}
}
cout << "插入排序的結果為:";
for (int i = 1; i < MAXSIZE + 1; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
int main()
{
int * array;
array = new int [MAXSIZE];
make_sorted(array);
insert_sort(array);
cout << endl;
delete [] array;
return 0;
}
演示結果: