冒泡排序法:
public class 冒泡排序 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a={4,20,3,9,14,23,10,59};
for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length-i-1;j++)
{
if(a[j]>a[j+1])
{//把这里改成大于,就是升序了
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
选择排序法:
public class 选择排序 {
/**
* 区别在于:冒泡算法,每次比较如果发现较小的元素在后面,
* 就交换两个相邻的元素。而选择排序算法的改进在于:
* 先并不急于调换位置,先从A[1]开始逐个检查,
* 看哪个数最小就记下该数所在的位置P
* ,等一躺扫描完毕,再把A[P]和A[1]对调,
* 这时A[1]到A[10]中最小的数据就换到了最前面的位置。
* 所以,选择排序每扫描一遍数组,只需要一次真正的交换,
* 而冒泡可能需要很多次。比较的次数是一样的。
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[] = { 20, 29, 21, 45, 68, 15, 3, 5 };
for (int i = 0; i < a.length - 1; i++) {
//查找选择最小元素值的下标索引值
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[i]) {//把这里改成大于,就是升序了
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int c = 0; c < a.length; c++) {
System.out.println(a[c]);
}
}
}