単純選択ソート(C&Java実装)
2695 ワード
C言語版
Java言語版
#include <stdio.h>
#define SWAP( a, i, j ) { t = a[i]; a[i] = a[j]; a[j] = t; }
void disp_array( int a[], int n )
{
int i;
for( i = 0; i < n; ++i )
printf( "%d ", a[i] );
printf( "
" );
}
int select_min( int a[], int n, int i )
{
int min_v = a[i], j, id = i;
for( j = i + 1; j < n; ++j )
{
if( a[j] < min_v )
{
min_v = a[j]; id = j;
}
}
return id;
}
void select_sort( int a[], int n )
{
int i, id, t;
for( i = 0; i < n; ++i )
{
id = select_min( a, n, i );
if( i != id )
SWAP( a, id, i );
}
}
int main()
{
int n = 8;
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
printf( "Before sorting: " );
disp_array( a, n );
select_sort( a, n );
printf( "After sorting: " );
disp_array( a, n );
return 0;
}
Java言語版
public class TestSort {
public static void dispArray( int a[] ) {
for( int i = 0; i < a.length; ++i )
System.out.print( a[i] + " " );
System.out.println();
}
public static void swap( int a[], int i, int j ) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
private static boolean less( int a[], int i, int j ) {
return a[i] < a[j];
}
private static boolean less( int a, int b ) {
return a < b;
}
private static int selectMin( int [] a, int i, int j ) {
if( i > j ) return -1;
int minVal = a[i], minId = i;
for( int k = i + 1; k <= j; ++k ) {
if( less( a[k], minVal ) ) {
minVal = a[k]; minId = k;
}
}
return minId;
}
/*
* selection sort
*/
public static void selectSort( int [] a ) {
int minId;
for( int i = 0; i < a.length; ++i ) {
minId = selectMin( a, i, a.length - 1 );
if( i != minId ) swap( a, i, minId );
}
}
public static void main( String[] args ) {
int a[] = { 100, 49, 38, 65, 97, 76, 13, 27, 49 };
System.out.print( "Before sorting: " );
dispArray( a );
selectSort( a );
System.out.print( "Simple Selection sorting: " );
dispArray( a );
}
}