基本介紹
- 中文名:冒泡排序
基本介紹
算法原理
算法分析
代碼舉例
public class main{
public static void main(String ARGs[]) throws IOException
{
int num[] = new int;
int i = 0;
int temp = 0;
int sum = 0;
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
temp = Integer.parseInt(buf.readLine());
if(temp != -1)
{
num[i] = temp;
i++;
sum += temp;
}
else
{
break;
}
}
System.out.println("平均數:" + (sum / (i - 1)));
PoPo popo = new PoPo(num, i);
popo.sort();
}
}java.io.*;
public class main{
public static void main(StringARGs[]) throws IOException
{
int num[] = new int;
int i = 0;
int temp = 0;
int sum = 0;
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
temp = Integer.parseInt(buf.readLine());
if(temp != -1)
{
num[i] = temp;
i++;
sum += temp;
}
else
{
break;
}
}
System.out.println("平均數:" + (sum / (i - 1)));
PoPo popo = new PoPo(num, i);
popo.sort();
}
}public class PoPo{
int num[] = new int;
int flag = 0;
int length = 0;
public PoPo()
{
}
public PoPo(int[] Num, int i)
{
for(int j = 0; j < i; j++)
{
this.num[j] = Num[j];
}
length = i;
}public void sort()
{
int i = 0;
int j = 0;
int temp = 0;
for(i = 0; i < length; i++)
{
for(j = i; j < length - 1; j++)
{
if(num[i] > num[j + 1])
{
temp = num[j + 1];
num[j + 1] = num[i];
num[i] = temp;
}
}
}
System.out.print("after sort:");
for(i = 0 ; i < length; i++)
System.out.print(num[i] + " ");
System.out.println("");
}
}
先編譯PoPo.java,在編譯main.java
執行主程式時,輸入一個數字敲個回車,輸入-1時結束。
第2種情況:public class Sort{
public static void sort(String arg)
{
String[] args=arg.split(",");
for(int i=0;i<args.length;i++)
{
for(int j=0;j<args.length-i-1;j++)
{
int a=Integer.parseInt(args[j]);
int b=Integer.parseInt(args[j+1]);
if(a>b)
{
a=a^b;
b=a^b;
a=a^b;
}
args[j]=String.valueOf(a);
args[j+1]=String.valueOf(b);
}
}
for(int i=0;i<9;i++)
{
System.out.print(args[i]+",");
}
}
public static void main(String[] args)
{
sort("2,10,3,50,78,22,34,30,65");
}
}
第3種情況:public class Sort{
public static void main(String args[])
{
int[] m =
{ 2, 8, 43, 3, 33 };
int[] n = sort(m);
for (int i = 0; i < m.length; i++)
{
System.out.println(n[i] + "\n");
}
}/* 冒泡排序算法 */
public static int[] sort(int[] m)
{
int intLenth = m.length;
/*執行intLenth次*/
for (int i = 0; i < intLenth; i++)
{
/*每執行一次,將最da的數排在後面*/
for (int j = 0; j < intLenth - i - 1; j++)
{
int a = m[j];
int b = m[j + 1];
if (a > b)
{
m[j] = b;
m[j + 1] = a;
}
}
}
return m;
}
}