将0~N打乱顺序,然后排序
生活随笔
收集整理的這篇文章主要介紹了
将0~N打乱顺序,然后排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
/*將0~N打亂順序,然后排序*/#include <stdio.h> #include <stdlib.h> #include <time.h>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
總結
以上是生活随笔為你收集整理的将0~N打乱顺序,然后排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android应用植入广告SDK,获取广
- 下一篇: 对话框的创建