-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcocktailsort.c
66 lines (64 loc) · 1.78 KB
/
cocktailsort.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
#include "cocktailsort.h"
void cocktail_sort(data array[], int len) {
int begin = 0; // array is to be sorted from position begin to end+1
int end = len-1;
int i; // currently scanning position: comparing array[i] and array[i+1]
int new_end = begin;
int new_begin = end;
while (begin < end) { // while array is not completely sorted
new_end = begin;
for (i = begin; i < end; i++) // scan from begin to end
if (array[i] > array[i+1]) {
data tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
new_end = i;
}
end = new_end;
new_begin = end;
for (i = end-1; i >= begin; i--) // scan from end to begin
if (array[i] > array[i+1]) {
data tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
new_begin = i;
}
begin = new_begin;
}
}
void cocktail_sort_debug(data array[], int len, STAT *stat) {
int begin = 0; // array is to be sorted from position begin to end+1
int end = len-1;
int i; // currently scanning position: comparing array[i] and array[i+1]
int new_end = begin;
int new_begin = end;
data tmp; // temporary variable used to swap elements
stat->space++;
stat->allo++;
while (begin < end) { // while array is not completely sorted
new_end = begin;
for (i = begin; i < end; i++) { // scan from begin to end
if (array[i] > array[i+1]) {
tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
new_end = i;
stat->swap++; // count swappings
}
stat->comp++; // count comparisons
}
end = new_end;
new_begin = end;
for (i = end-1; i >= begin; i--) { // scan from end to begin
if (array[i] > array[i+1]) {
tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
new_begin = i;
stat->swap++; // count swappings
}
stat->comp++; // count comparisons
}
begin = new_begin;
}
}