Chinaunix首页 | 论坛 | 博客
  • 博客访问: 220997
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-11 09:47:08

/*
 * tpop(2): Algorithms and Data Structures
 * created on Mar 3, 2011
 */
#include

/* NELEMS macro: computes the number of elements in the array */
#define NELEMS(array) (sizeof(array) / sizeof(array[0]))


void quicksort(int [], int);
void swap(int [], int, int);

/* quicksort main: quick sort an array */
int main(int argc, char *argv[])
{
        int i;
        int array[] = {1, 3, 5, 7, 9, 2, 6, 4,10,22,8};
    /* print the array before sort */
        printf("The original array  is \n");
        for (i = 1; i < NELEMS(array); i++)
                printf ("%d ", array[i]);
        printf ("\n");

        /* print the array after sort */    
        quicksort(array, NELEMS(array));
        printf("The sorted array  is \n");
         for (i = 1; i < NELEMS(array); i++)
             printf ("%d ", array[i]);
         printf("\n");

}


/* quicksort: sort v[0]..v[n-1] into increasing order */
void quicksort(int v[], int n)
{
        int i, last;
        if (n <= 1) /* nothing to do */
                return;
        swap (v, 0, rand() % n); /* move pivot elem to v[0] */
        last = 0;
        for (i = 1; i < n; i++) /* partition */
                if (v[i] < v[0])
                        swap(v, ++last, i);
        swap(v, 0, last); /* restore pivot */
        quicksort(v, last); /* recursively sort */
        quicksort(v+last+1, n-last-1); /* each part */
}

/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
        int temp;
        temp = v[i];
        v[i] = v[j];
        v[j] = temp;
}

阅读(314) | 评论(0) | 转发(0) |
0

上一篇:tpop(1): Style

下一篇:Hadoop MapReduce Tutorial

给主人留下些什么吧!~~