黑马程序员技术交流社区
标题:
数组的排序,选择排序和冒泡排序
[打印本页]
作者:
红凉梦
时间:
2016-1-20 13:47
标题:
数组的排序,选择排序和冒泡排序
选择排序
#include
<stdio.h>
int
main()
{
int
a[]={
1
,
3
,
4
,
8
,
5
,
2
};
int
b=(
sizeof
a)/
sizeof
(
int
);
int
tempIndex=
0
;
for
(
int
i=
0
; i<
6
; i++)
{
tempIndex=i;
for
(
int
j=i+
1
; j<
6
; j++)
{
if
(a[tempIndex]>a[j])
{
tempIndex=j;
}
}
// printf("%d ",a[tempIndex]);
int
temp;
temp=a
;
a
=a[tempIndex];
a[tempIndex]=temp;
printf(
"%d "
,a
);
}
printf(
"\n"
);
}
冒泡排序
//
/
//
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int a[10];//定义十个数
for (int i=0; i<10; i++) {
a
=arc4random_uniform(100)+1;//随机1-100的数字存储
printf("%d ",a
);
}
printf("\n");
//利用选择排序进行排列
for (int i=0; i<10; i++) {
for (int j=i+1; j<9; j++) {
int temp;
if (a
>a[j]) {
temp=a
;
a
=a[j];
a[j]=temp;
}
}
}//可优化
for (int i=0; i<10; i++) {
printf("%d ",a
);
}
printf("\n");
//
//运用冒泡排序
int temp;
for(int i=0;i<10;i++)
for (int j=0; j<9; j++) {
if (a[j]>a[j+1]) {
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
for (int i=0; i<10; i++) {
printf("%d ",a
);
}
printf("\n");
printf("Hello, World!\n");
return 0;
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2