{//只要前面的元素大于后面的元素,立即交换
if (a[j] > a[j + 1])
{int temp =a[j];
a[j]= a[j + 1];
a[j+ 1] =temp;
}
}
cout<<"第" <
print(a, n);
}
cout<<"最终结果" <
print(a, n);
endTime&#61;clock();
cout<<"Totle Time :" <<(double)(endTime - startTime)*1000 / CLOCKS_PER_SEC <<"ms" <
system("pause");return 0;
}
Java实现
package com.xgt.util;import java.lang.reflect.Method;/**
* &#64;author cjy
* &#64;Date2018/6/19 15:25.
*/
public class BubbleSort {
static void print(int[] arr,int n)
{
for(int k&#61;0;k
System.out.print(arr[k]&#43;",");}
System.out.println();}
private static final int a[] &#61; {5,9,7,6,1,8,13,4};public static void main(String[]args) throws NoSuchMethodException {
methodExecutionTime(BubbleSort.class.getMethod("bubbleSort", new Class[]{int[].class}));}
public static void bubbleSort(int[]a){
int n&#61; a.length; for(int i&#61;0;i
for(int j&#61;0;j
if(a[j]>a[j&#43;1]){
int temp&#61; a[j]; a[j] &#61; a[j&#43;1]; a[j&#43;1] &#61; temp;}
}
System.out.println("第"&#43;(i&#43;1)&#43;"个步骤"); print(a,n);}
System.out.println("最终结果"); print(a,n);}
/**
* 计算方法执行时间
* &#64;param method 所有方法都是Method类的对象
*/
private static void methodExecutionTime (Method method) {
long begin&#61; System.nanoTime();try {
method.invoke(new BubbleSort(), a);} catch (Exception e) {
e.printStackTrace();}
long end&#61; System.nanoTime() - begin; System.out.println(method.getName() &#43; "方法耗时&#xff1a;" &#43; end/1000 &#43; "纳秒");}
}
Python实现
#!/usr/bin/env python#coding:utf-8
importtimedefbubbleSort(nums):for i in range(len(nums)-1): #这个循环负责设置冒泡排序进行的次数
for j in range(len(nums)-i-1): #&#xff4a;为列表下标
if nums[j] > nums[j&#43;1]:
t&#61;nums[j];
nums[j]&#61; nums[j&#43;1];
nums[j&#43;1] &#61;t;print"第",i&#43;1,"步骤"
print(nums)returnnums
nums&#61; [5,9,7,6,1,8,13,4];
start&#61;time.time()
bubbleSort(nums)
end&#61;time.time()print (end-start)*1000000,"微秒"
语言
Java
Python
C&#43;&#43;
平均时间(ms)
1322
999
24
Java运行时间控制台截图
Python运行时间截图
C&#43;&#43;运行时间截图
效率排行&#xff1a;C&#43;&#43;>Python>Java