6 #include "lib_vstack.h"
8 void sort_selection(int list
[], int lo
, int hi
)
11 for(j
= lo
; j
< hi
; j
++)
13 s
= sort_get_smallest(list
, j
,hi
);
14 sort_swap(list
, j
, s
);
18 void sort_insertion(int list
[], int lo
, int hi
)
21 for(j
= lo
+1; j
<= hi
; j
++)
25 while(k
>= lo
&& key
< list
[k
])
34 void sort_heap(int num
[], int n
)
37 for(k
= n
/2; k
>= 1; k
--) sort_shift_down(num
[k
], num
, k
, n
);
38 for(k
= n
; k
> 1; k
--)
42 sort_shift_down(item
, num
, 1, k
-1);
46 void sort_quick(int a
[], int lo
, int hi
)
50 int dp
= sort_partition(a
, lo
, hi
);
51 sort_quick(a
, lo
, dp
-1);
52 sort_quick(a
, dp
+1, hi
);
56 void swap(int list
[], int i
, int j
) {
62 int partition2(int a
[], int lo
, int hi
)
67 do --hi
; while(a
[hi
] > pivot
);
68 do ++lo
; while(a
[lo
] < pivot
);
69 if(lo
< hi
) swap(a
, lo
, hi
);
74 void sort_quick_norecurse(int a
[], int lo
, int hi
)
76 int stackItems
= 1, maxStackItems
= 1;
78 Stack_Head
*pHead
= vstack_new();
79 Stack_Node
*pNode
= NULL
;
80 Sort_Data
*pData
= NULL
;
81 pNode
= vstack_push(pHead
);
82 pNode
->pData
= sort_data_new(lo
, hi
);
83 while(pHead
->count
!= 0)
86 pNode
= vstack_peek(pHead
);
89 if(pData
->left
< pData
->right
){
90 dp
= partition2(a
, pData
->left
, pData
->right
);
91 if(dp
- pData
->left
+ 1 < pData
->right
- dp
) {
92 vstack_push_data(pHead
, sort_data_new(dp
+1, pData
->right
)); /* update the push function to accept data */
93 vstack_push_data(pHead
, sort_data_new(pData
->left
, dp
));
95 vstack_push_data(pHead
, sort_data_new(pData
->left
, dp
));
96 vstack_push_data(pHead
, sort_data_new(dp
+1, pData
->right
));
100 if(stackItems
> maxStackItems
)maxStackItems
= stackItems
;
104 void sort_shift_down(int key
, int num
[], int root
, int last
)
106 int bigger
= 2 * root
;
107 while(bigger
<= last
)
110 if(num
[bigger
+1] > num
[bigger
]) bigger
++;
111 if(key
>= num
[bigger
]) break;
112 num
[root
] = num
[bigger
];
119 int sort_partition(int a
[], int lo
, int hi
)
123 for(j
= lo
+ 1; j
<= hi
; j
++)
128 sort_swap(a
, last_sm
, j
);
131 sort_swap(a
, lo
, last_sm
);
135 int sort_get_smallest(int list
[], int lo
, int hi
)
138 for(j
= lo
+ 1; j
<= hi
; j
++)
139 if(list
[j
] < list
[small
]) small
= j
;
143 void sort_swap(int list
[], int i
, int j
)
150 Sort_Data
*sort_data_new(int a
, int b
)
152 Sort_Data
*pData
= malloc(sizeof(Sort_Data
));