Advertisement
Guest User

QuickSort improved

a guest
Apr 23rd, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.20 KB | None | 0 0
  1. program AlphaSorter;
  2. type
  3.   wordsContainer = record
  4.       Values : array[1..100] of string;  
  5.       Length : integer;
  6.   end;
  7.  
  8. var wordsList : wordsContainer;
  9.  
  10.     procedure FillWordArray(var arr : wordsContainer);
  11.     var i:integer;
  12.     begin
  13.         write('How many words do you want to enter? N = ');
  14.         readln(arr.Length);
  15.  
  16.         for i:=1 to arr.Length do
  17.         begin
  18.             write('Word(',i,'): ');
  19.             readln(arr.Values[i]);
  20.         end;
  21.     end;
  22.  
  23.  
  24.     procedure SwapElemetsAt(var arr : wordsContainer; i, j :integer);
  25.      var aux:string;
  26.      begin
  27.             aux := arr.Values[i];
  28.           arr.Values[i]:=arr.Values[j];
  29.           arr.Values[j]:=aux;
  30.       end;
  31.      
  32.      
  33.     procedure QuickSort(var arr : wordsContainer; low : integer; high : integer);
  34.     var i, j:integer; pivot:string;
  35.     begin
  36.      i     := low;
  37.      j     := high;
  38.      pivot := arr.Values[low + ((high-low) div 2)];
  39.      
  40.      while i <= j do
  41.      begin
  42.         while arr.Values[i] < pivot do
  43.           i := i + 1;
  44.          
  45.         while arr.Values[j] > pivot do
  46.           j := j - 1;
  47.          
  48.         if i <= j then
  49.         begin
  50.           SwapElemetsAt(arr, i, j);
  51.           i := i + 1;
  52.           j := j - 1;
  53.         end;
  54.        
  55.         // Recursion
  56.         if low < j then
  57.            QuickSort(arr, low, j);
  58.            
  59.         if i < high then
  60.            QuickSort(arr, i, high);
  61.      end;
  62.     end;
  63.  
  64.     procedure StringArraySorter(var arr : wordsContainer);
  65.     begin
  66.       if arr.Length = 0 then
  67.          exit;
  68.        
  69.       QuickSort(arr, 1, arr.Length);
  70.     end;
  71.    
  72.  
  73.  
  74.    
  75.     procedure DisplayStringArray(var arr : wordsContainer);
  76.     var i:integer;  isNotFirstDisplayingChannel : boolean;
  77.     begin
  78.         writeln;
  79.         write('Words list: ');
  80.      
  81.         isNotFirstDisplayingChannel := false;
  82.         for i:=1 to arr.Length do
  83.         begin
  84.           if isNotFirstDisplayingChannel then write(', ');
  85.           write(arr.Values[i]);
  86.           isNotFirstDisplayingChannel := true;
  87.         end;
  88.     end;
  89.    
  90. BEGIN
  91.     FillWordArray(wordsList);
  92.    
  93.     StringArraySorter(wordsList);
  94.    
  95.     DisplayStringArray(wordsList);
  96. END.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement