sorting - Using BubbleSort in C# to sort Integers, But Want to Move Whole Object -
i have implemented simple bubblesort sort tasks based on priority , looks this
int temp = 0; (int write = 0; write < taskstructure.tasksarray.count; write++) { (int sort = 0; sort < taskstructure.tasksarray.count - 1; sort++) { if (taskstructure.tasksarray[sort].taskpriority > taskstructure.tasksarray[sort + 1].taskpriority) { temp = taskstructure.tasksarray[sort + 1].taskpriority; taskstructure.tasksarray[sort + 1].taskpriority = taskstructure.tasksarray[sort].taskpriority; taskstructure.tasksarray[sort].taskpriority = temp; } } }
this works fantastic, , sorts them in correct order, however, literally swaps integers around in column , not object (task) linked to.
for example:
i have 2 tasks
name: testname1 desc: testdesc1 priority: 5
name: testname2 desc: testdesc2 priority: 3
after bubblesort:
name: testname1 desc: testdesc1 priority: 3
name: testname2 desc: testdesc2 priority: 5
but needs (move actual object):
name: testname2 desc: testdesc2 priority: 3
name: testname1 desc: testdesc1 priority: 5
hope makes clearer, there way can move object(task) priority linked well?
you have change swapping procedure (the innermost block of code) , remove int temp = 0
line @ beginning:
var temp = taskstructure.tasksarray[sort + 1]; taskstructure.tasksarray[sort + 1] = taskstructure.tasksarray[sort]; taskstructure.tasksarray[sort] = temp;
but note, can use array.sort
method this:
array.sort(taskstructure.tasksarray, (x, y) => x.taskpriority - y.taskpriority);
Comments
Post a Comment