洗牌算法 (C语言)

#include "stdafx.h" #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> #include <windows.h> #include "OBJC_DEF.h" using namespace std; void print(int *arr, int count) { for (int i = 0; i < count; ++i) { cout << arr[i] << " "; } cout << endl; } BOOL shuffle(int *outArray, int outArrayCount, int from, int to) { NSAssert((to - from + 1 == outArrayCount), @"out array count does not equal to the count based on 'from' to 'to' variable "); BOOL ret = NO; // 1. first fill the outArray as sorted value. for (int index = 0; index < outArrayCount; ++index) { outArray[index] = from + index; } srand((unsigned int) time(0)); int tempIndex = 0; int tempInt = 0; for(int i = outArrayCount - 1; i >0; --i) { int r = rand(); //cout << "r :" << r << " "; Sleep(100); tempIndex = r % (i); tempInt = (outArray)[i]; (outArray)[i] = (outArray)[tempIndex]; (outArray)[tempIndex] = tempInt; } // test print(outArray, outArrayCount); // just print the value. return ret; } void testShuffle() { int from = 11; int to = 20; int count = 10; int *arr = (int *)malloc(sizeof(int) * count); for (int i=0; i < 1000; i++) { shuffle(arr, count, from, to); } int a; cin >> a; free(arr); }

你可能感兴趣的:(c,算法,语言,include)