Recursive implementation:
public void selectionSort (int a[ ], int n) {
if (n <= 1) return;
int maxPos = 0; // position of the max element
int k;
for ( k = 1; k < n; k++)
if (a [ k ] > a [ maxPos ] ) maxPos = k;
int temp = a [ maxPos ];
a [ maxPos ] = a[ n-1 ];
a [ n-1 ] = temp;
selectionSort (a, n-1);
}
if (n <= 1) return;
int maxPos = 0; // position of the max element
int k;
for ( k = 1; k < n; k++)
if (a [ k ] > a [ maxPos ] ) maxPos = k;
int temp = a [ maxPos ];
a [ maxPos ] = a[ n-1 ];
a [ n-1 ] = temp;
selectionSort (a, n-1);
}
Iterative implementation:
public void selectionSort (int a [ ], int n){
while (n > 1) {
int k, maxPos = 0;
for ( k = 1; k < n; k++)
if (a [ k ] > a [ maxPos ] ) maxPos = k;
while (n > 1) {
int k, maxPos = 0;
for ( k = 1; k < n; k++)
if (a [ k ] > a [ maxPos ] ) maxPos = k;
int temp = a [ maxPos ];
a [ maxPos ] = a[ n-1 ];
a [ n-1 ] = temp;
n--;
}
a [ maxPos ] = a[ n-1 ];
a [ n-1 ] = temp;
n--;
}
}
댓글 없음:
댓글 쓰기