排序算法之Java实现1——冒泡排序算法

来源:互联网 发布:获取intent数据 编辑:程序博客网 时间:2024/06/11 05:49
package com.sorts;


public class BubbleSort {


/**
* 冒泡排序,大数下沉到最末位置
* 时间复杂度为:
* 最好:O(n);平均:O(n^2);最坏:O(n^2)
* 空间复杂度: O(1)
* @param a[]
*/
public static void bubblesortbig(int[] a){
int i,j;
int temp;//最大值
for(i=0; i<a.length; i++)
{
temp = a[0];
for(j=1; j<a.length-i; j++)
{
if(a[j]>temp){
temp = a[j];
}
else{
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
a[a.length-i-1] = temp;
}
}

/**
* 冒泡排序,小数上浮到最首位置
* @param a
*/
public static void bubblesortsmall(int[] a){
int i,j;
int temp;//最小值
for(i=0; i<a.length; i++)
{
temp = a[a.length-1];
for(j=a.length-1; j>i; j--)
{
if(a[j-1]<temp){
temp = a[j-1];
}
else{
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
a[i] = temp;
}
}

public static void main (String args[])
{
int i;
int[] a = {2,6,7,3,1,5,0};
bubblesortbig(a);
//bubblesortsmall(a);
for(i=0; i<a.length; i++){
System.out.println("a["+i+"]="+a[i]);
}
}
}
0 0