本文共 2020 字,大约阅读时间需要 6 分钟。
开始慢慢复习算法,巩固基础。
从最简单的排序开始,主要是理解排序的思想,之前看了很多次书,从来没有实际过,发现结果都忘记了。
可以用扑克牌来想象排序的过程,只不过有些操作对于计算机来说要复杂一些,比如:
// Defines the entry point for the console application.//#include "stdafx.h"#include "windows.h"#include "time.h"const int N = 10;int O = 0;int* GenRandom(){ srand( (unsigned)time( NULL ) ); int* a = new int[N]; for (int i = 0; i < N; i++) { a[i] = rand() * rand(); } return a;}void swap(int& a, int& b){ int temp = 0; temp = a; a = b; b = temp;}//small -> largevoid SelectionSort(int* ua){ //round times,遍历N次 for (int i = 0; i < N-1; i++) { //printf("round %d \r\n", i); //for (int i = 0; i < N; i++) //{ // printf("a[%d]=%d \r\n",i, *(ua+i)); //} int nMinIndex = i;//最小值的索引//每次确定一个值,从第一个值开始。。。第二次从第二个值开始 for (int j = i + 1; j < N; j++) { if( ua[nMinIndex] >= ua[j] ) { nMinIndex = j; } O++; } swap(ua[i], ua[nMinIndex] ); }}SYSTEMTIME StartTime = {0};FILETIME StartFileTime = {0};SYSTEMTIME EndTime= {0};FILETIME SEndFileTime= {0};int _tmain(int argc, _TCHAR* argv[]){ int* a = GenRandom(); GetSystemTime(&StartTime); printf("timeBefore %d:%d:%d \r\n", StartTime.wMinute, StartTime.wSecond, StartTime.wMilliseconds); SelectionSort(a); GetSystemTime(&EndTime); printf("timeAfter %d:%d:%d \r\n", EndTime.wMinute, EndTime.wSecond, EndTime.wMilliseconds); printf("times %d \r\n", O); return 0;}
转载地址:http://umlgb.baihongyu.com/