冒泡排序:
例:
index 0 1 2 3 4 5 6
8 6 2 9 1 7 4
step:
1: 0和1比,大的往后放
6 8 2 9 1 7 4
2: 1和2比,...........
6 2 8 9 1 7 4
依次比较,每一次循环的结果就是将最大的数放到当前比较对象里的最后面。
public void bubble(int array[]){
int temp;
for(int i=array.length-1;i>0;i--)
{
for(int j =0;j<i;j++)
{
if(array[j]>array[j+1])
{
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
for(int i =0;i<array.length;i++)
System.out.println("输出的第"+(i+1)+"个数为:"+array[i]);
}
选择排序:
循环过程:
1,找到最小值放到第一个位置
2,找到次最小值放到第二个位置
依次下去。
public void selectSort(int array[])
{
int temp;
for (int i = 0; i < array.length; i++)
{
for (int j = i + 1; j < array.length; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
System.out.println("输出的第" + (i + 1) + "个数:" + array[i]);
}
}
插入排序:
循环过程:
1,把前两个数顺序弄对
2,把前三个数顺序弄对
依次下去。
public void insert(int array[])
{
int temp;
for (int i = 1; i < array.length; i++)
{
temp = array[i];
int j = i;
while (j > 0 && array[j - 1] > temp)
{
array[j] = array[j - 1];
array[j - 1] = temp;
j--;
}
System.out.print("输出的数组第" + i + "次排序为: ");
for (j = 0; j <= i; j++)
{
System.out.print(" " + array[j]);
}
System.out.println();
}
}