Follow me on Twitter to receive updates, free scripts and ongoing announcements!

Quicksort array of string

Written by Codes Tips on May 10, 2009 – 1:33 pm -

Quicksort it’s an algorithm that it’s very efficient when you wanna sort an array of any type: string, integer, real. I will show you how to sort an array of string, it can be modified easily to sort other types of array.
Quicksort it’s efficient because it’s having a sorting complexity of O(n* log2(n)). An usual sorting algorithm like bubble sort or merge sort it’s taking O(n^2), which it’s very inefficient for array with over 5000 elements.
I will write an implementation of this algorithm in Delphi.
The Quicksort algorithm it’s very similar to divide and conquer algorithm because it splits the array into to sub arrays, sort those sub arrays and put them together after into 1 array sorted. For sorting those array it uses a pivot that it’s positioned in the middle of the array and put in the left, strings that are lower and in the right, the strings that are higher. So for doing this it uses a recursive function because for every sub array divides again in 2 sub array and sort them. So after sorting each sub array , we will have in the final step all the array sorted.

Here is an implementation of Quicksort array of string in Delphi.
First declare a type of array string:

type arraystrings=array[1..100000] of string;

Quicksort algorithm:

procedure QuickSort(var A: arraystrings; Lo, Hi: Integer);
 
procedure Sort(l, r: Integer);
var
  i, j,aux: integer;
  y,x:string;
begin
  i := l; j := r; x := a[(l+r) DIV 2];
  repeat
    while strIcomp(pchar(a[i]),pchar(x))<0 do i := i + 1;
    while StrIComp(pchar(x),pchar(a[j]))<0 do j := j - 1;
    if i <= j then
    begin
 
      y := a[i]; a[i] := a[j]; a[j] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sort(l, j);
  if i < r then Sort(i, r);
end;
 
begin 
  Sort(Lo,Hi);
 
end;

Tags: ,
Posted in Algorithms, Codes, Delphi |

2 Comments to “Quicksort array of string”

  1. Codes Tips » Blog Archive » Remove duplicates from file Says:

    [...] you should use QuickSort algorithm because if you have over 5000 phrases or words, the application will freeze. The complexity of the [...]

  2. Codes Tips » Blog Archive » Binary search in string array Says:

    [...] assume that we have a sorted array. To sort an array of string efficiently you can use for example Quicksort algorithm , that was previously described, to obtain a good complexity. Of course, you should use binary [...]

Leave a Comment

You must be logged in to post a comment.


Plugintaylor.com - Plugintaylor and Affiliate Store