好久之前就想準備寫博客來鞏固自己學習到的知識了,但是人太懶,一直都沒正式開始寫。今年6月份就要畢業了,沒拿到畢業證前不準備開始找工作,趁着這段空閒時間,寫寫博客,複習自己學到的知識。
不知道從哪裏開始寫,準備根據《算法導論》裏面的算法,依次寫下去。
===================================================================================
插入排序
插入排序爲什麼要稱爲插入排序呢?就是通過將值插入到它應該存在的位置來實現排序。
假設存在數組arr[0, ..., n],我們從arr[i](i從1開始,到n-1結束)開始取值(作爲key),然後將key和i之前的元素進行比較,直到找到比key小的元素的,那麼這個比key小的元素的後面那個位置即爲key的正確位置。在將key和arr[i-1, ..., 0]之間的元素進行比較的同時,我們還要將比較過的元素後移。即arr[i] = arr[i-1]。
廢話說完了,上代碼:
// InsertionSort.h
#pragma once
class InsertionSort
{
private:
int *data; // 待排序的數據
int length;
public:
InsertionSort(int* &d, int size):data(d), length(size) {}
~InsertionSort()
{
if(data != NULL)
{
delete data;
data = NULL;
}
}
void output() const;
void sort();
void swap(int i, int j);
};
// InsertionSort.cpp
#include <iostream>
#include "InsertionSort.h"
void InsertionSort::output() const
{
int i = 0;
while(i < length)
{
std::cout<<data[i]<<" ";
i++;
}
std::cout<<"\n";
}
void InsertionSort::sort()
{
for(int i = 1; i < length; i++)
{
int key = data[i]; // 待插入的值
for(int j = i - 1; j >= 0; j--)
{
int temp = data[j];
if(key >= temp)
{
break;
}
swap(j, j + 1);
}
}
}
// 數值交換方法,只對整型數據有效
void InsertionSort::swap(int i, int j)
{
data[i] ^= data[j];
data[j] ^= data[i];
data[i] ^= data[j];
}
// Main.cpp
#include <iostream>
#include <time.h>
#include "InsertionSort.h"
// 獲取[1,500]範圍內的隨機數
int proRandNum()
{
return rand() % 500 + 1;
}
int main()
{
using namespace std;
srand((unsigned)time(NULL)); // 設置隨機數種子
int size = 20;
int *data = new int[size];
for(int i = 0; i < size; i++)
{
data[i] = proRandNum();
}
InsertionSort *sort = new InsertionSort(data, size);
cout<<"before sorted:\n";
sort->output();
cout<<"after sorted:\n";
sort->sort();
sort->output();
system("pause");
return 0;
}