-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathPancakeSort.c
71 lines (63 loc) · 1.32 KB
/
PancakeSort.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
#include <stdio.h>
#include <stdlib.h>
void doFlip(int *, int, int);
int pancakeSort(int *list, unsigned int length)
{
if (length < 2)
return 0;
int i, a, max_num_pos, moves;
moves = 0;
for (i = length;i > 1;i--)
{
max_num_pos = 0;
for (a = 0;a < i;a )
{
if (list[a] > list[max_num_pos])
max_num_pos = a;
}
if (max_num_pos == i - 1)
continue;
if (max_num_pos)
{
moves ;
doFlip(list, length, max_num_pos 1);
}
doFlip(list, length, i);
}
return moves;
}
void doFlip(int *list, int length, int num)
{
int swap;
int i = 0;
for (i;i < --num;i )
{
swap = list[i];
list[i] = list[num];
list[num] = swap;
}
}
void printArray(int list[], int length)
{
int i;
for (i = 0;i < length;i )
{
printf("%d ", list[i]);
}
}
int main(int argc, char **argv)
{
int n;
scanf("%d",&n);
int list[n];
int i;
printf("enter the n elements of array:\n");
for (i = 0;i < n;i )
scanf("%d", &list[i]);
printf("\nOriginal: ");
printArray(list, n);
int moves = pancakeSort(list, n);
printf("\nSorted: ");
printArray(list, n);
printf(" - with a total of %d moves\n", moves);
}