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
Vaibhav BabrekarVaibhav Babrekar 

Can anyone help me to solve quick sort algorithm using Apex code

I want to sort the elements of a list in ascending order by using the quick sort algorithm. 

Thanks in Advance
PriyaPriya (Salesforce Developers) 

Hey Vaibhav,

Can you kindly elaborate the requirement?

Thanks,

Priya Ranjan

Vaibhav BabrekarVaibhav Babrekar
Hi Priya,
I want to sort list of integers using the Quick sort algorithm. Such as if I provide list as {20,30,70,10,40} so after quick sort it shoud return me sorted list as {10, 20, 30, 40, 70}
PriyaPriya (Salesforce Developers) 
OK got it. Thanks for the clarification.

So lets say you have some list of integer, then pass those ineteger to list like below :-
List<Integer> intergerList = new List<Integer> {20,30,70,10,40} ;
Now for ASCENDING ORDER
 
List<Integer> integerList = new List<integer>{20,30,70,10,40} ;

for(Integer i = 0 ; i < integerList.size() ; i ++) {
for(integer j = i+1 ; j <= integerList.size() -1 ; j ++ ){
  integer x = 0 ;
  if(integerList[i] >  integerList[j]){
   x = integerList[i]  ;
   integerList[i] = integerList[j]  ;
   integerList[j]  = x;
   system.debug(integerList) ;
  }
}
}

Now for DESCENDING ORDER
 
List<Integer> integerList = new List<integer>{20,30,70,10,40} ;

for(Integer i = 0 ; i < integerList.size() ; i ++) {
for(integer j = i+1 ; j <= integerList.size() -1 ; j ++ ){
  integer x = 0 ;
  if(integerList[i] <  integerList[j]){
   x = integerList[i]  ;
   integerList[i] = integerList[j]  ;
   integerList[j]  = x;
   system.debug(integerList) ;
  }
}
}

 Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.

Thanks & Regards,

Priya Ranjan