Witam
Zaczynam uczyć się o algorytmach. Jestem na samym początku. Mam problem z sortowaniem przez wybieranie. Napisałem kod, ale nie działa poprawnie. Podaje ciąg liczb 14, 1900, 198,1, 2 i otrzymuje wynik posortowany 2, 1, 14, 198, 1900 zamiast 1, 2, 14, 198, 1900. Korzystam z książki Wprowadzenie do Algorytmów Cormen, Leiserson etc. Tutaj nie dotarłem jeszcze do niczego o stabilności algorytmów, coś o tym czytałem na necie, ale z tego co rozumiem, to ten algorytm powinien być niestabilny do liczb powtarzających się w ciągu, a nie zupełnie innych..... czy jednak źle rozumiem i powinien poczytać o stabilności algorytmów? Poniżej zamieszczam kod:
import java.util.Scanner;
public class SortowaniePrzezWybieranie {
public static void SelectionSort (int [] tableForSorting){
int placeHolder;
for (int i =0; i<tableForSorting.length; i++){
int minValue = i;
for (int j=i+1; j<tableForSorting.length; j++){
if (tableForSorting[j]<tableForSorting[minValue]){
minValue=j;
placeHolder =tableForSorting[minValue];
tableForSorting[minValue]=tableForSorting[i];
tableForSorting[i]=placeHolder;
}
}
}
System.out.println("tablica po sortowaniu");
for (int printData: tableForSorting){
System.out.println(printData);
}
}
public static void main (String [] args){
System.out.println("Ile liczb ma zawierać ciąg?: ");
Scanner input = new Scanner(System.in);
int numOfElements = input.nextInt();
int [] tableWithoutSorting = new int [numOfElements];
for (int i=0; i<tableWithoutSorting.length; i++){
System.out.println("Wprowdz element nr." + (i+1)+ ":");
tableWithoutSorting[i]=input.nextInt();
}
System.out.println("Tabela przed posortowaniem");
for (int tableWithoutSortingForPrint: tableWithoutSorting){
System.out.println(tableWithoutSortingForPrint);
}
SelectionSort(tableWithoutSorting);
}
}