标签:区分 对比 alt swa out ima package swap 第一个

1.冒泡排序
比较相邻元素,如果第一个比第二个大,就交换位置,每一次交换,当前
package BubbleSort;
public class Test
{
public static void main(String[] args)
{
int[] arr = {1,3,5,7,3,6,7,4,8,34,6};
Test test = new Test();
test.bubbleSort(arr);
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
public void bubbleSort(int[] num)
{
int temp = 0;
for(int i = 0; i < num.length - 1; i++)
{
for(int j = i + 1; j < num.length; j++)
{
if(num[j-1] > num[j])
{
temp = num[j];
num[j] = num[j - 1];
num[j - 1] = temp;
}
}
}
}
}
2. 选择排序
从所有的数字中找到最小的数,放在第一个位置,然后从剩余的数字中找出次小的数,放在第二个位置,然后从剩下的数字中找出再次小的数,放在第三个位置......以此类推,直到所有的数据全部有序。
package SelectionSort;
public class Test
{
public static void main(String[] args)
{
int[] a = {4,2,1,6,3,6,0,-5,4,3};
Test test = new Test();
test.selectionSort(a);
for(int i = 0; i < a.length; i++)
{
System.out.print(a[i] + " ");
}
}
public void selectionSort(int[] source)
{
for(int i = 0; i < source.length; i++)
{
for(int j = i + 1; j < source.length; j++)
{
if(source[i] > source[j])
{
swap(source, i, j);
}
}
}
}
private void swap(int[] source, int x, int y)
{
int temp = source[x];
source[x] = source[y];
source[y] = temp;
}
}
注意将选择排序和冒泡排序进行区分:冒泡排序是将相邻的数据进行对比,而选择排序是将下标为i和j的数据进行对比(每次选出当前数据集中最小的)。

标签:区分 对比 alt swa out ima package swap 第一个
原文地址:http://www.cnblogs.com/Mr24/p/6626776.html