-
Notifications
You must be signed in to change notification settings - Fork 368
/
pancake_sort.c
64 lines (56 loc) · 1.12 KB
/
pancake_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
#include <stdio.h>
void flip(int arr[], int i)
{
int start = 0;
while (start < i)
{
int temp = arr[start];
arr[start] = arr[i];
arr[i] = temp;
start++;
i--;
}
}
int findMaxIndex(int arr[], int n)
{
int maxIndex = 0;
for (int i = 1; i < n; i++)
{
if (arr[i] > arr[maxIndex])
{
maxIndex = i;
}
}
return maxIndex;
}
void pancakeSort(int arr[], int n)
{
for (int currSize = n; currSize > 1; currSize--) // Reduces the size of the array by 1 in each iteration
{
int maxIndex = findMaxIndex(arr, currSize);
if (maxIndex != currSize - 1)
{
flip(arr, maxIndex);
flip(arr, currSize - 1);
}
}
}
int main()
{
int arr[] = {6, 3, 9, 2, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
pancakeSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}