Search code examples
c#sortingobjectbubble-sort

Using BubbleSort in C# to sort Integers, But Want to Move Whole Object


I have implemented a simple BubbleSort to sort my tasks based on their priority and it looks like this

int temp = 0;
for (int write = 0; write < taskStructure.TasksArray.Count; write++)
{
    for (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, and it sorts them in the correct order, however, it literally swaps the integers around in that column only and not the object (Task) that it is linked to.

For example:

I have two tasks

Name: TestName1 Desc: TestDesc1 Priority: 5
Name: TestName2 Desc: TestDesc2 Priority: 3

After my BubbleSort:

Name: TestName1 Desc: TestDesc1 Priority: 3
Name: TestName2 Desc: TestDesc2 Priority: 5

But it needs to do (Move the actual object):

Name: TestName2 Desc: TestDesc2 Priority: 3
Name: TestName1 Desc: TestDesc1 Priority: 5

Hope this makes it clearer, is there any way that I can move the object(task) that the priority is linked to as well?


Solution

  • You just have to change the swapping procedure (the innermost block of code) like this and remove the int temp = 0 line at the beginning:

    var temp = taskStructure.TasksArray[sort + 1];
    taskStructure.TasksArray[sort + 1] = taskStructure.TasksArray[sort];
    taskStructure.TasksArray[sort] = temp;
    

    But note, you can also use the Array.Sort method like this:

    Array.Sort(taskStructure.TasksArray, (x, y) => x.taskPriority - y.taskPriority);