I have created two functions that sorts a list using bubble sort, but I would like to change the sort style to quick sort.
I found this quick sort algorithm
http://snipd.net/quicksort-in-c
These are my two functions:
protected void sort_by_section_name()
{
int num1, num2;
for (var i = section_names.Count - 1; i > 0; i -= 1)
{
for (var j = 0; j < i; j += 1)
{
num1 = get_number_from_section(section_names[j]);
num2 = get_number_from_section(section_names[j + 1]);
if (num1 > num2)
{
swap_list_strings(section_names, j, j + 1);
swap_object_items(item_group_list, j, j + 1);
}
}
}
}
protected void sort_items()
{
int num1, num2;
List<SPListItem> temp;
for (var k = 0; k < item_group_list.Count; k += 1)
{
temp = (List<SPListItem>)item_group_list[k];
for (var i = temp.Count - 1; i > 0; i -= 1)
{
for (var j = 0; j < i; j += 1)
{
num1 = Convert.ToInt32((temp[j])[ORDER_BY_COLUMN]);
num2 = Convert.ToInt32((temp[j + 1])[ORDER_BY_COLUMN]);
if (num1 > num2)
{
swap_list_items(temp, j, j + 1);
}
}
}
}
}
For sort_items, its an array of arrays, so the bubble sort stuff is in a for loop.
I don’t understand how to change these two functions into using the quicksort.
Can someone please help me?
So you have a
List<SPListItem>and you want them sorted, using an efficient sorting algorithm (aka not bubblesort) based on the numeric value of some field. This is easy, and doesn’t involve you re-implementing quicksort.It’s also worth noting that when possible it’s usually better to sort your data on the database, rather than on the webserver. You should be able to add an
Order Byclause to the CAML query generating thoseSPListItems and let it do the sort.It appears that you’re sorting two different data structures that are “parallel” (the item at the same index of both structures “belong” together). This is generally undesirable. While there are ways to perform a sort on both structures, what you really should be doing is making a single structure such that each item holds onto everything that logically represents that one item. In many cases this means creating a new
classthat has properties for each piece of data. You can then populate a collection of this new composite class and sort that.