#include #define MAXSIZE 30 struct _st_list { int sqlist[MAXSIZE]; int size; }; struct _st_list a = {{0, }, 0}; static inline int *_get_head(struct _st_list *p) { return p->sqlist; } static inline int *_get_tail(struct _st_list *p) { return p->sqlist + p->size; } void show(struct _st_list *p) { int *ptr = _get_head(p); int *end = _get_tail(p); printf("%d:\n", p->size); for (; ptr < end; ptr++) { printf("%d ", *ptr); } printf("\n"); } void insert(struct _st_list *p, int i, int x) { if (p->size == MAXSIZE) return; if (i < 0) return; if (i > p->size) return; int *ptr = _get_tail(p); int *end = _get_head(p) + i; for (; ptr > end; ptr--) { *ptr = *(ptr - 1); } *ptr = x; p->size += 1; } int delete(struct _st_list *p, int i) { if (p->size == 0) return 0; if (i < 0) return 0; if (i >= p->size) return 0; int *ptr = _get_head(p) + i; int *end = _get_tail(p); int del = *ptr; for (; ptr < end; ptr++) { *ptr = *(ptr + 1); } p->size -= 1; return del; } static int _more_than(int a, int b) { return a > b; } static int _less_than(int a, int b) { return a < b; } static int _trace_pick(struct _st_list *p, int (*match)(int, int)) { if (!p->size) return 0; int *ptr = _get_head(p); int *end = _get_tail(p); int fetch = *ptr++; for (; ptr < end; ptr++) { if (match(*ptr, fetch)) fetch = *ptr; } return fetch; } int min(struct _st_list *p) { return _trace_pick(p, _less_than); } int max(struct _st_list *p) { return _trace_pick(p, _more_than); } static int *_iter_bisearch(int *s, int *e, int x) { if (e - s < 2) { if (x > *s) return e; else return s; } int *m = s + (e - s) / 2; if (x > *m) return _iter_bisearch(m, e, x); else return _iter_bisearch(s, m, x); } static int _bisearch(struct _st_list *p, int x) { int *ptr = _get_head(p); int *end = _get_tail(p); return _iter_bisearch(ptr, end, x) - _get_head(p); } void biinsert(struct _st_list *p, int x) { insert(p, _bisearch(p, x), x); } static void _iter_sort(int *s, int *e) { if (e <= s) return; int v = *s; int *p = s; int *q = e; for (;;) { while ((p < q) && (*q >= v)) q -= 1; *p++ = *q; if (p >= q) { p = q; break; } while ((p < q) && (*p <= v)) p += 1; *q-- = *p; if (p >= q) break; } *p = v; _iter_sort(s, p - 1); _iter_sort(p + 1, e); } void sort(struct _st_list *p) { if (p->size < 2) return; _iter_sort(_get_head(p), _get_tail(p) - 1); } int main() { printf("========= start ==========\n"); insert(&a, 0, 7); insert(&a, 0, 6); insert(&a, 0, 3); insert(&a, 0, 9); insert(&a, 0, 1); insert(&a, 0, 4); insert(&a, 0, 2); insert(&a, 0, 8); show(&a); sort(&a); show(&a); biinsert(&a, 5); show(&a); printf("########## end ##########\n"); return 0; }