/* This is the prompt:
starts with an unsorted array a
output: sorted array a.
Find the smallest element in the array a[1: n], call it a[j]. Swap it with a[0], if it is smaller than a[0]. Repeat this process with index 1, 2, ... until the who array is sorted. */
public class assing2 {
public static void main(String args[])
{
//array of ints
int[] A = new int[] {33, 20, 8, 11, 5};
int min_id = 0;
int temp_i = 0;
//int temp_max = 0;
for (int i = 0; i < A.length; i++)
{
min_id = i;
temp_i = A[i];
for (int j = 1; j < A.length; j++)
{
if (A[min_id] > A[j])
{
min_id = j;
}
}
A[i] = A[min_id];
A[min_id] = temp_i;
}
System.out.println("Sorted array");
for ( int i = 0; i < A.length; i++)
{
System.out.println(A[i]);
}
}
}
This is the output
Sorted array
5
20
11
33
8
When I run it in the debugger i can see that the first 2 iterations of the first for loop looks like its working but after that it unsorted what was sorted.
Whats is wrong with my logic?