aboutsummaryrefslogtreecommitdiffstats
path: root/com32/elflink/modules/sort.c
blob: bec0ef2ab7d036493409d36ca8ee0fe09954f7cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * sort.c - Sample ELF module providing a quick sort function
 *
 *  Created on: Aug 11, 2008
 *      Author: Stefan Bucur <stefanb@zytor.com>
 */

#include <stdlib.h>
#include <sys/module.h>

/**
 * sort_init - Module entry point.
 */
static int sort_init() {
	return 0; // Nothing to do; return success
}


static inline void swap(int *x, int *y) {
	int tmp;
	tmp = *x;
	*x = *y;
	*y = tmp;
}

static inline int randint(int l, int u) {
	return l + (rand() % (u-l+1));
}

/**
 * quick_sort_range - A small and efficient version of quicksort.
 * @nums: The numbers to sort
 * @l: The lower index in the vector (inclusive)
 * @u: The upper index in the vector (inclusive)
 *
 * The implementation is taken from "Beautiful Code", by O'Reilly, the
 * book students received from Google as a gift for their acceptance
 * in the GSoC 2008 program. The code belongs to Jon Bentley, who
 * wrote the third chapter of the book. Since ELF modules were written
 * as part of this program, the author of the module considered
 * the book had to be put at some use. :)
 */
static void quick_sort_range(int *nums, int l, int u) {
	int i, m;
	if (l >= u) return;

	swap(&nums[l], &nums[randint(l, u)]);

	m = l;
	for (i = l+1; i <= u; i++) {
		if (nums[i] < nums[l])
			swap(&nums[++m], &nums[i]);
	}

	swap(&nums[l], &nums[m]);

	quick_sort_range(nums, l, m-1);
	quick_sort_range(nums, m+1, u);
}


void quick_sort(int *nums, int count) {
	quick_sort_range(nums, 0, count-1);
}

/**
 * sort_exit - Module exit point.
 */
static void sort_exit() {
	// Nothing to do
}

// Define entry and exit points.
MODULE_INIT(sort_init);
MODULE_EXIT(sort_exit);