Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Implement a word insertion_sort ( arr -- ). In other words, this word expects a pointer to an array of numbers on the stack. It
Implement a word insertion_sort ( arr -- ). In other words, this word expects a pointer to an array of numbers on the stack. It pops this pointer from the stack and pushes nothing new onto the stack. The side effect this word should have is to arrange the elements in arr in sorted order, using Insertion Sort. You are welcome to define helper words such as dup2 that you can use in your implementation of Insertion Sort. Indeed, defining such helper words is common practice among FORTH programmers because the stack effects of more complex words such as insertion_sort are hard to understand if we implement these words using only the built-in words. Assume we want to implement a word sum that expects (a pointer to) an array of numbers on the top of the stack and replaces it with the sum of all array elements. Here is how we would implement it. The word itself is annotated with the typical stack effect annotation. It shows that the array arr is popped from the stack and the sum of its elements sum (arr) is pushed onto the stack. I have annotated each of the other lines with the state of the stack once execution reaches the end of this line, in order to allow you to trace the execution. Whenever I use >r an r> to move data between the data stack and the recursion stack, I use the notation / to visualize the contents of both stacks. This code uses the word dup2 we defined earlier to duplicate the top two elements on the stack
Implement a word insertion_sort ( arr -- ). In other words, this word expects a pointer to an array of numbers on the stack. It pops this pointer from the stack and pushes nothing new onto the stack. The side effect this word should have is to arrange the elements in arr in sorted order, using Insertion Sort. You are welcome to define helper words such as dup2 that you can use in your implementation of Insertion Sort. Indeed, defining such helper words is common practice among FORTH programmers because the stack effects of more complex words such as insertion_sort are hard to understand if we implement these words using only the built-in words.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started