您的位置:首页 > 编程语言 > C语言/C++

排序算法之冒泡排序——java/c++/c实现

2014-12-01 14:01 183 查看
//1. java实现
import java.util.*;
public class  helloword{
public static void main(String[] args){
int a[] = new int[10];
int i, j, temp;
for (i = 0; i < 10; i++){
a[i] = new Random().nextInt(10);
}
System.out.println("没排序前的数据:");
for (i = 0; i < 10; i++){
System.out.println(a[i]+" ");
}
for (i = 0; i < 10 - 1; i++){
for (j = 0; j < 10 - i - 1; j++){
if (a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}

}
System.out.println("排序后的数据:");
for (i = 0; i < 10; i++){
System.out.println(a[i]+"");
}
}
}

//2.c实现
#include<stdio.h>
#include<time.h>
void main()
{
int i, j, temp;
int a[10];
srand((unsigned int)time(NULL));
for (i = 0; i < 10; i++)
{
a[i] = rand() % 10;
}
printf("排序前的数据为:\n");
for (i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
printf("\n");
//冒泡排序
for (i = 0; i < 10 - 1; i++)
for (j = 0; j < 10 - 1 - i; j++)
{
if (a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
printf("排序后的数据为:\n");
for (i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}

//3. c++实现
#include<iostream>
using namespace std;
int main()
{
int a[10];

cout << "排序前的数据:" << endl;
for (int i = 0; i < 10; i++)
a[i] = rand() %  10;
for (i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
//冒泡排序
for (i = 0; i < 10 - 1; i++)
for (int j = 0; j < 10 - i - 1; j++)
if (a[j] > a[j+1])
swap(a[j], a[j+1]);
//排序后的数据
cout << "排序后的数据:" << endl;
for (i = 0; i < 10; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐