算法---選擇排序

選擇排序



#include<stdio.h>

#define n 10
void main( void ) 
{




//input
int data[n];
int nElems = 0;
int i = 0;
int j = 0;
int temp = 0;

printf( "Please input the number( n<=10 ) of the data:" );
scanf( "%d", &nElems );

if ( nElems > n ) {


printf( "Input error!");


} else {


printf( "Please input the number:");

for ( i = 0; i <nElems; i ++ ) {
scanf( "%d", &data[i] );
}


printf( "the data you input:");

for ( i = 0; i < nElems; i ++ ) {


printf( "%d\t", data[i] );

}


printf( "\n" );


//sort
for ( i = 0; i < nElems-1; i ++  ) {


for ( j = i+1; j < nElems; j ++ ) {

if ( data[i] > data[j] ) {
//exchange
temp = data[j];
data[j] = data[i];
data[i] = temp;
}
}
}



//output
printf( "after sorted:");
for ( i = 0; i < nElems; i ++ ) {


printf( "%d\t", data[i] );

}


printf( "\n" );
}

}



和冒泡排序一樣,都是for的描述過程

0,確定變化量

1,確定for之間的關係,嵌套或者平行

發佈了33 篇原創文章 · 獲贊 11 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章