forked from zkpig123/mycode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsert_sort.c
72 lines (66 loc) · 1.88 KB
/
insert_sort.c
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
#include "insert_sort.h"
void _insert_sort_incremental_get_reverse_num (int cards[], size_t card_num, size_t *reverse_num)
{
*reverse_num = 0;
for (size_t i = 1; i <= card_num - 1; i++){
int cur = cards[i];
long long j;
for (j = i - 1; j >= 0 && cards[j] > cur; j--){
cards[j + 1] = cards[j];
}
cards[j + 1] = cur;
*reverse_num += i - j - 1;
}
}
void _insert_sort_decremental_get_reverse_num (int cards[], size_t card_num, size_t *reverse_num)
{
*reverse_num = 0;
for (size_t i = 1; i <= card_num - 1; i++){
int cur = cards[i];
size_t j;
for (j = i - 1; j >= 0 && cards[j] < cur; j--){
cards[j + 1] = cards[j];
}
cards[j + 1] = cur;
*reverse_num += i - j - 1;
}
}
int insert_sort_get_reverse_num (int cards[], size_t card_num, int sort_order, size_t *reverse_num)
{
if (cards == NULL ||card_num <= 0 || sort_order == 0 || reverse_num == NULL) return -1;
*reverse_num = 0;
if (card_num == 1) return 0;
if (sort_order > 0) _insert_sort_incremental_get_reverse_num(cards, card_num, reverse_num);
else _insert_sort_decremental_get_reverse_num(cards, card_num, reverse_num);
return 0;
}
void _insert_sort_incremental (int cards[], size_t card_num)
{
for (size_t i = 1; i <= card_num - 1; i++){
int cur = cards[i];
long long j;
for (j = i - 1; j >= 0 && cards[j] > cur; j--){
cards[j + 1] = cards[j];
}
cards[j + 1] = cur;
}
}
void _insert_sort_decremental (int cards[], size_t card_num)
{
for (size_t i = 1; i <= card_num - 1; i++){
int cur = cards[i];
size_t j;
for (j = i - 1; j >= 0 && cards[j] < cur; j--){
cards[j + 1] = cards[j];
}
cards[j + 1] = cur;
}
}
int insert_sort (int cards[], size_t card_num, int sort_order)
{
if (cards == NULL ||card_num <= 0 || sort_order == 0) return -1;
if (card_num == 1) return 0;
if (sort_order > 0) _insert_sort_incremental(cards, card_num);
else _insert_sort_decremental(cards, card_num);
return 0;
}