Selection Sort

I was given this algorithm

ALGORITHM SelectionSort(A[0...n-10)

//Sorts a given array by selection sort

//Input: An array A[0....n-1] of orderable elements

//Output: Array A[0.....n-1] sorted in ascending order

for i = 0 to n-2 do

min = 1

for j = i + 1 to n-1 do

if A[j[ < A[min]min = j

swap A[ i ] and A[min]

And I wrote this following java program to match the algorithm

for (int i=0; i<array2.length-2; i++) {

int min = i;

for (int j=i+1; j><array2.length-1; j++) {

if (array2[j] >< array2[min]){

min = j;

//... Exchange elements

temp = array2[ i ];

array2[ i ] = array2[min];

array2[min] = temp;

}//end if

}//end of inner for loop

}//end

The problem is that it does not execute right as it does not sort the numbers as given. Can somebody please tell me where I went wrong? Thanks

null

[963 byte] By [JuppieJuxa] at [2007-10-3 5:56:58]
# 1

1) for i=0 to n-k

means for (int i=0; i<n-k+1; i++)

, not for (int i=0; i<n-k; i++)

in the both for loops.

2) array2[min]

should be array2[ i]

in the if clause.

perkelea at 2007-7-15 0:38:18 > top of Java-index,Other Topics,Algorithms...
# 2

I changed it to this:

for (int i=0; i < array2.length-2+1; i++) {

int min = i;

for (int j=i+1; j < array2.length-1+1; j++) {

if (array2[j ] < array2[i ]){

//... Exchange elements

temp = array2[i ];

array2[i ] = array2[min];

array2[min] = temp;

}//end if

}//end of inner for loop

}//end of outer for loop

and it still won't work

JuppieJuxa at 2007-7-15 0:38:18 > top of Java-index,Other Topics,Algorithms...
# 3
Now the bug is that you removed the line min = j;The whole variable min is useless as it only holds the value of i or j (and not even the correct one of those) which you could use directly.
perkelea at 2007-7-15 0:38:18 > top of Java-index,Other Topics,Algorithms...