• Amar Kumaraiah
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

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