Selection Sort

Description du code

Exemple de tri par sélection

Code source ou contenu du fichier

  1. program selectionSort;
  2. function maxValueIndex(var a : array of integer; minIndex, maxIndex : integer);
  3. {Pre: a defined
  4. maxIndex>=minIndex;
  5. minIndex>=0;
  6. a[minIndex..maxIndex] defined
  7.  Post: for each i into minIndex..maxIndex, a[maxIndex] >= a[i]
  8. }
  9. var tempMax : integer;
  10. begin
  11. if minIndex >= maxIndex then maxValueIndex := minIndex;
  12. else begin
  13. tempMax := maxValueIndex(a, minIndex+1, maxIndex);
  14. if a[minIndex]<a[tempMax]
  15. then maxValueIndex := tempMax;
  16. else maxValueIndex := minIndex;
  17. end
  18. end;
  19. procedure swap(var a : array of integer; i, j : integer);
  20. {Pre: a defined
  21. j>i;
  22. i>=0;
  23. a[i] defined
  24. a[j] defined
  25.  Post: a[i]=old value at a[j] et a[j]=old value at a[i]
  26. }
  27. var temp: integer;
  28. begin
  29. temp := a[i];
  30. a[i] := a[j];
  31. a[j] := temp;
  32. end;
  33. procedure selectionSort(var a : array of integer; arraySize : integer);
  34. {Pre: a defined
  35. arraySize>=0;
  36. a indexed from 0 to arraySize -1
  37. for each i into 0..arraySize-1, a[i] defined
  38.  Post: for each i into 0..arraySize-2, a[i] <= a[i+1]
  39. }
  40. var i : integer;
  41. begin
  42. for i := arraySize downto 0 do
  43. swap(a, i, maxValueIndex(a,1,i));
  44. end;
  45. {main program
  46. }
  47. begin
  48. const maxIndice = 7;
  49. var testArray : packed array[0..maxIndice] of integer;
  50. testArray[0] := 8;
  51. testArray[1] := 4;
  52. testArray[2] := 6;
  53. testArray[3] := 2;
  54. testArray[4] := 13;
  55. testArray[5] := 4;
  56. testArray[6] := 1;
  57. testArray[7] := 20;
  58. var i : integer;
  59. writeln('Unsorted array :');
  60. for i:=0 to maxIndice do
  61. writeln('value ', testArray[i], ' at index ', i);
  62. selectionSort(testArray, maxIndice+1);
  63. writeln('Sorted array :');
  64. for i:=0 to maxIndice do
  65. writeln('value ', testArray[i], ' at index ', i);
  66. end.

Autres extraits de codes en Pascal

Document créé le 05/10/2009, dernière modification le 28/10/2018
Source du document imprimé : https://www.gaudry.be/sniplet-rf-pascal/tri-selection.pas.html

L'infobrol est un site personnel dont le contenu n'engage que moi. Le texte est mis à disposition sous licence CreativeCommons(BY-NC-SA). Plus d'info sur les conditions d'utilisation et sur l'auteur.