《算法导论》上看到的伪代码
好久没写c代码来,我写的c代码
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; int* randomize(int n); int main(int argc, char** argv) { srand((unsigned)time(0)); int* s = randomize(100); for (int i=0; i<100; i++) { cout << s[i] << ","; } cout << endl; return 0; } void swap(int* s, int a, int b) { int t = s[b]; s[b] = s[a]; s[a] = t; } int* randomize(int n) { static int *s = new int(n); for (int i=0; i<n; i++) { s[i]=i; cout << s[i] << ","; } cout << endl; for (int i=0; i<n; i++) { int k = random()%(n-i) + i; //k=[i+1,n-i] cout << "k=" << k << endl; swap(s[i],s[k]); } return s; }