PR2-Hummel-3024753/PR2pvl/src/SelectionSort.java

129 lines
2.4 KiB
Java

public class SelectionSort {
private boolean change;
private int temp;
public static int[] selectionSort(int[] arr) {
int tmp;
int index = 0;
for(int i=0; i < arr.length; i++) {
tmp = arr[i];
for(int j = 0; j < arr.length; j++) {
if(arr[j] < tmp) tmp = arr[j];
index = j;
}
arr[index] = arr[i];
arr[i]=tmp;
}
return arr;
}
public void sortLSG(int data[])
{
for (int i = 0; i < data.length - 1; i++) {
System.out.println(i + 1 + ". iteration");
// Find the index of the minimum in unsorted part of array
int minIndex = i;
for (int j = i + 1; j < data.length; j++) {
if (data[j] < data[minIndex])
minIndex = j;
}
// Swap the minimum element with first element from unsorted part, unless they are the same
if(i != minIndex) {
System.out.print("Found minimum: " + data[minIndex] + ", swapping with " + data[i] + " => ");
temp = data[minIndex];
data[minIndex] = data[i];
data[i] = temp;
}
else
System.out.print("Minimum: " + data[minIndex] + " is on the right spot, no swapping => ");
printArray(data);
}
}
// Function to print an array
public void printArray(int data[])
{
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
System.out.println();
}
public static void selectionsortUebung(int[] arr){
int temp;
for(int i = 0; i<arr.length; i++){
temp = arr[i];
int k=i;
while(k<arr.length){
if(arr[k] < temp) temp = arr[k];
k++;
}
arr[k]=arr[i];
arr[i]=temp;
}
}
public static void selectionsortUebungcgpt(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int minIndex = i;
int k = i;
while (k < arr.length) {
if (arr[k] < arr[minIndex]) {
minIndex = k;
}
k++; // ❗ ganz wichtig
}
// Tauschen
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}