It smells of homework. What you need to do is sort the array, but minimize the cost of swaps. So this is an optimization problem, not a sorting problem.
The greedy algorithm, despite this work, all you do is that you fix the solution by first replacing the cheapest one (finding out where in the list it belongs). This, however, is not necessarily optimal.
As long as you never change the same element twice, the greedy algorithm should be optimal.
In any case, back to the dynamic programming material, just create a decision tree using recursion, and then prune the tree when you find more optimal solutions. This is a fairly simple recursion.
If you have a more complex sorting algorithm, you will have much more problems than with dynamic programming, so I suggest you start with a simple, slow sorting of O(n^2) . And build on top of it.
Instead of providing you with a solution, I would like to explain how dynamic programming works in my own words.
- The first thing you need to do is figure out an algorithm that will investigate all possible solutions (it can be a really stupid brute force algorithm).
- Then you implement this with recursion, because dynamic programming is based on the ability to quickly find overlapping routines, ergo regression.
- With each recursive call, you look where you are in your solution and check where you have already computed this part of the decision tree, if you did, you can check if the current solution is more optimal if you continue, otherwise you finish with this branch of the problem.
- When you come to a final solution, you will solve the problem.
Think of each recursive call as a snapshot of a partial solution. It is your job to understand how each recursive call fits together in the final optimal solution.
This is what I recommend you:
- Write a recursive sorting algorithm
- Add a parameter to the recursive function that supports the cost of this execution path, add this value as you sort the array. For each possible exchange, at any given point, another recursive call is made (this will lead to branching of the decision tree).
- Whenever you realize that the cost of the solution that you are currently studying is higher than what you already have elsewhere, interrupt (just return).
To be able to answer the last question, you need to maintain a shared memory area in which you can index, depending on where you are, you are a recursive algorithm. If there is a pre-calculated value, you simply return this value and do not continue processing (this is a reduction that makes it quick).
Using this method, you can even base your decision on a permutation sorting algorithm, it will probably be very slow or intense, because it is stupid when it comes to branches or pruning, but you donβt need a specific sorting algorithm to make this work. It will be more effective to go this route.
Good luck