插入排序

来源:互联网 发布:mac希腊字母怎么打 编辑:程序博客网 时间:2024/05/29 04:15

好久之前就想准备写博客来巩固自己学习到的知识了,但是人太懒,一直都没正式开始写。今年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 onceclass 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;}



0 0
原创粉丝点击