博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
将0~N打乱顺序,然后排序
阅读量:5989 次
发布时间:2019-06-20

本文共 1425 字,大约阅读时间需要 4 分钟。

hot3.png

/*将0~N打乱顺序,然后排序*/#include 
#include
#include
int swap(int *a, int *b){ int tmp; tmp = *a; *a = *b; *b = tmp; return 0;}/* right place:a[t] = t;wrong place: a[t] != t * every while loop put one element to a right place, if the * element in wrong place.Because int a[], there are at most * [size] element in wrong place, this function cost time O(n) * */int sort(int a[], int size){ int i; for(i =0; i < size; i++) { while(a[i] != i) { /*after this swap, a[t] = t if t = a[i]*/ swap(&a[i], &a[a[i]]); } }}int shuffle(int a[], int size){ for( size--; size > 0; size--) { int k = rand()%size; if(k != size) { swap(&a[k], &a[size]); } } return 0;}int disp_array(int a[], int size){ int i; for(i = 0; i < size; i++) { printf("%d ", a[i]); } printf("\n");}int main(){ srand((unsigned int)(time(NULL))); int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; int len_a = sizeof(a)/sizeof(a[0]); shuffle(a, len_a); disp_array(a, len_a); sort(a, len_a); disp_array(a, len_a); return 0;}

转载于:https://my.oschina.net/u/240262/blog/81253

你可能感兴趣的文章