算法---冒泡算法


冒泡算法


#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; i ++  ) {


for ( j = 0; j < nElems-1; j ++ ) {

if ( data[j+1] < data[j] ) {
//exchange
temp = data[j+1];
data[j+1] = data[j];
data[j] = temp;
}
}
}



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


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

}


printf( "\n" );
}

}


直接上代碼,沒啥好說的!


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