function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jhartfieldjhartfield 

Sort a list of SelectOptions using basic quicksort

I had a need to sort several small lists of SelectOptions (<100 items) and wrote this basic quicksort to do it.  I decided to share it in case anyone else finds it useful.

 

Be advised this will probably only work for smaller lists because the call stack may get large, in which case you will want to use one of the more complex versions of quicksort which are posted around the forums. 

 

// This is a simple quicksort algorithm to sort a SelectOption list (dropdown)
// by label alphabetically.
public static List<SelectOption> SortOptionList(List<SelectOption> ListToSort)
{
if(ListToSort == null || ListToSort.size() <= 1)
return ListToSort;

List<SelectOption> Less = new List<SelectOption>();
List<SelectOption> Greater = new List<SelectOption>();
integer pivot = 0;

// save the pivot and remove it from the list
SelectOption pivotValue = ListToSort[pivot];
ListToSort.remove(pivot);

for(SelectOption x : ListToSort)
{
if(x.getLabel() <= pivotValue.getLabel())
Less.add(x);
else if(x.getLabel() > ListToSort[pivot].getLabel()) Greater.add(x);
}
List<SelectOption> returnList = new List<SelectOption> ();
returnList.addAll(SortOptionList(Less));
returnList.add(pivotValue);
returnList.addAll(SortOptionList(Greater));
return returnList;
}

 

 

 

 

Message Edited by jhartfield on 03-15-2010 11:17 AM
Paul BourdeauxPaul Bourdeaux

Pretty major error in your code.  I found it while unit testing...

 

this line:

else if(x.getLabel() > ListToSort[pivot].getLabel()) Greater.add(x);	

 

should read

else if(x.getLabel() > pivotValue.getLabel()) Greater.add(x);	

 

 

Once fixed, this code works great!  Thanks for posting it!

Amar KumaraiahAmar Kumaraiah
Thanks for saving an hour of my time