將0~N打亂順序,而後排序

/*將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;

}
相關文章
相關標籤/搜索