一、交换两个变量的三种方法
int x = 3 ;
int y = 7 ;
1.使用第三变量
# include <stdio.h>
int main ( )
{
int x = 3 ;
int y = 7 ;
int temp = 0 ;
temp = x;
x = y;
y = temp ;
return 0 ;
}
2.使用和运算
# include <stdio.h>
int main ( )
{
int x = 3 ;
int y = 7 ;
x = x + y;
y = x - y;
x = x - y;
return 0 ;
}
3.使用位运算
# include <stdio.h>
int main ( )
{
int x = 3 ;
int y = 7 ;
x = x ^ y;
y = x ^ y;
x = x ^ y;
return 0 ;
}
二、3个整数排序
# include <stdio.h>
void Sort ( int a, int b, int c)
{
if ( a< b)
{
int temp = a;
a = b;
b = temp;
}
if ( a< c)
{
int temp = a;
a = c;
c = temp;
}
if ( b< c)
{
int temp = b;
b = c;
c = temp;
}
printf ( "%d %d %d\n" , a, b, c) ;
}
int main ( )
{
int a, b, c;
scanf ( "%d %d %d" , & a, & b, & c) ;
Sort ( a, b, c) ;
return 0 ;
}
三、冒泡排序多个数(从小到大)
# include <stdio.h>
void sort_arrary ( int * arr)
{
int temp = 0 ;
for ( int i = 0 ; i < 9 ; i++ )
{
for ( int j = 0 ; j < 9 - i; j++ )
{
if ( arr[ j] > arr[ j+ 1 ] )
{
temp = arr[ j] ;
arr[ j] = arr[ j+ 1 ] ;
arr[ j+ 1 ] = temp;
}
}
}
for ( int i = 0 ; i < 10 ; i++ )
{
printf ( "%d " , * ( arr+ i) ) ;
}
}
int main ( )
{
int arr[ 10 ] = { 0 } ;
for ( int i = 0 ; i < 10 ; i++ )
{
scanf ( "%d" , arr + i) ;
}
sort_arrary ( arr) ;
return 0 ;
}