Reputation: 16931
I have records in the database with the sort order number. Now I want to create a UI with buttons UP and DOWN to reorder them. What is the best algorithm to make two functionsUp(record) and functionDown(record) in order to rearrange them by changing orderNum and them persist that number to the database.
Here is the example of what I'm trying to achieve (before foo=24, after foo=25):
Before pressing up on bar
id | name | orderNum
--------------------
1 | foo | 24
2 | bar | 25
3 | doe | 26
After
id | name | orderNum
--------------------
1 | foo | 25
2 | bar | 24
3 | doe | 26
Upvotes: 0
Views: 145
Reputation: 2308
If you are wanting to sort them on the UI, you should map each record in your ResultSet to a bean. Then you can have your bean implement the Comparable interface and use that to sort your collection.
If you want to sort on different fields, depending on which is selected you can also write Comparators for each of the fields and inject the Comparator for the selected column at runtime.
Upvotes: 0
Reputation:
Assuming that you are using Java Collections, you can write a class that implements Comparable
and use the utility Collections.sort()
. More info about ordering colletions here.
Upvotes: 1
Reputation: 3522
Assuming he doesn't want ask for the data from database again nd again, just to sort data he selected, why not quick sort algorithm?
Of course if I'm right. If not, just follow @ggrigery solution
Upvotes: 0