Selection Sort
Description du code
Exemple de tri par sélectionCode source ou contenu du fichier
Code Pascal (Selection Sort) (66 lignes)
program selectionSort; function maxValueIndex(var a : array of integer; minIndex, maxIndex : integer); {Pre: a defined maxIndex>=minIndex; minIndex>=0; a[minIndex..maxIndex] defined Post: for each i into minIndex..maxIndex, a[maxIndex] >= a[i] } var tempMax : integer; begin if minIndex >= maxIndex then maxValueIndex := minIndex; else begin tempMax := maxValueIndex(a, minIndex+1, maxIndex); if a[minIndex]<a[tempMax] then maxValueIndex := tempMax; else maxValueIndex := minIndex; end end; procedure swap(var a : array of integer; i, j : integer); {Pre: a defined j>i; i>=0; a[i] defined a[j] defined Post: a[i]=old value at a[j] et a[j]=old value at a[i] } var temp: integer; begin temp := a[i]; a[i] := a[j]; a[j] := temp; end; procedure selectionSort(var a : array of integer; arraySize : integer); {Pre: a defined arraySize>=0; a indexed from 0 to arraySize -1 for each i into 0..arraySize-1, a[i] defined Post: for each i into 0..arraySize-2, a[i] <= a[i+1] } var i : integer; begin for i := arraySize downto 0 do swap(a, i, maxValueIndex(a,1,i)); end; {main program } begin const maxIndice = 7; var testArray : packed array[0..maxIndice] of integer; testArray[0] := 8; testArray[1] := 4; testArray[2] := 6; testArray[3] := 2; testArray[4] := 13; testArray[5] := 4; testArray[6] := 1; testArray[7] := 20; var i : integer; writeln('Unsorted array :'); for i:=0 to maxIndice do writeln('value ', testArray[i], ' at index ', i); selectionSort(testArray, maxIndice+1); writeln('Sorted array :'); for i:=0 to maxIndice do writeln('value ', testArray[i], ' at index ', i); end.
Autres extraits de codes en Pascal
- Merge Sort Exemple de tri par fusion
- Selection Sort Exemple de tri par sélection
- Suite de Fibonacci Exemple de récursion en Pascal
- Suite de Fibonacci Exemple de méoïsation en Pascal
- Tous les extraits
English translation
You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.
Thank you in advance.
Document created the 05/10/2009, last modified the 28/10/2018
Source of the printed document:https://www.gaudry.be/en/sniplet-rf-pascal/tri-selection.pas.html
The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.