1+ #include < stdlib.h>
2+ #include < SDL3/SDL.h>
3+
4+ #include < InsertionSort.hpp>
5+ #include < List.hpp>
6+ #include < Rect.hpp>
7+ #include < Sort.hpp>
8+ #include < Utils.hpp>
9+
10+ namespace InsertionSort {
11+
12+ int GetStepCount (Rectangle* items) {
13+ Rectangle* array = CopyArray (items);
14+
15+ int stepCount = 1 ;
16+
17+ for (int index = 1 ; index < LIST_SIZE; ++index) {
18+ int key = array[index].value ;
19+ int j = index - 1 ;
20+
21+ while (j >= 0 && array[j].value > key) {
22+ array[j + 1 ].value = array[j].value ;
23+ j = j - 1 ;
24+
25+ // INCREMENT THE STEP COUNTER (CHECKING)
26+ stepCount++;
27+ }
28+ array[j + 1 ].value = key;
29+
30+ // INCREMENT THE STEP COUNTER
31+ stepCount++;
32+ }
33+
34+ free (array);
35+ return stepCount;
36+ }
37+
38+ SortSequence GetSequence (Rectangle* items) {
39+ Rectangle* array = CopyArray (items);
40+
41+ // INITIALLY RUN THE SORT TO CALCULATE THE TOTAL NUMBER OF STEPS
42+ int stepCount = GetStepCount (items);
43+
44+ SortSequence sort = create_sort_sequence (stepCount);
45+ sort.steps = (SortStep*) malloc (LIST_SIZE * stepCount * sizeof (SortStep));
46+
47+ int currentStep = 0 ;
48+ int offset;
49+
50+ for (int index = 1 ; index < LIST_SIZE; ++index) {
51+ int key = array[index].value ;
52+ int j = index - 1 ;
53+
54+ while (j >= 0 && array[j].value > key) {
55+ array[j + 1 ].value = array[j].value ;
56+ j = j - 1 ;
57+
58+ // RECORD THE SORTING STEP (SNAPSHOT OF THE ARRAY)
59+ for (int i = 0 ; i < LIST_SIZE; i++) {
60+ offset = (currentStep * LIST_SIZE) + i;
61+ sort.steps [offset].value = array[i].value ;
62+
63+ // SET RECTANGLE COLOR VALUE
64+ bool isCurrent = i == (index - 1 );
65+ bool isChecking = i == j;
66+ bool isOrdered = !isCurrent && !isChecking && i < index;
67+ sort.steps [offset].rect_color = GetRectangleColor (isOrdered, isCurrent, isChecking);
68+ }
69+ currentStep++;
70+ }
71+ array[j + 1 ].value = key;
72+
73+ // RECORD THE SORTING STEP (SNAPSHOT OF THE ARRAY)
74+ for (int i = 0 ; i < LIST_SIZE; i++) {
75+ offset = (currentStep * LIST_SIZE) + i;
76+ sort.steps [offset].value = array[i].value ;
77+
78+ // SET RECTANGLE COLOR VALUE
79+ bool isCurrent = i == (index - 1 );
80+ bool isChecking = i == j;
81+ bool isOrdered = !isCurrent && !isChecking && i < index;
82+ sort.steps [offset].rect_color = GetRectangleColor (isOrdered, isCurrent, isChecking);
83+ }
84+ currentStep++;
85+ }
86+
87+ // RECORD FINAL STEP (ORDERED LIST)
88+ for (int i = 0 ; i < LIST_SIZE; i++) {
89+ offset = (currentStep * LIST_SIZE) + i;
90+ sort.steps [offset].value = array[i].value ;
91+ sort.steps [offset].rect_color = rect_green_color;
92+ }
93+
94+ free (array);
95+ return sort;
96+ }
97+
98+ }
0 commit comments