一、冒泡排序
基本思想:两两比较相邻记录,如果反序则交换,直到没有反序的记录为止。
二、选择排序
基本思想:从序列中选择值最小的记录,并和第i个记录进行交换
Java代码实现如下:
public class Sort {
public void BubleSort(int a[]){
int p; //排序要经历的趟数,一般来说冒泡排序要经历元素个数减一趟
int temp,flag=0; //临时变量,用于保存交换的数据
for(p=a.length-1;p>0;p--){
flag = 0; //标志变量,如果某趟排序有数据交换就记为1
for(int i=0;i<p;i++){
if(a[i]>a[i+1]){ //如果前面的数大于后面的数,就交换顺序
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
flag = 1;
}
}
if(flag == 0){
break; //没有数据交换就可以直接跳出循环了
}
}
for(Integer i:a){
System.out.print(i+" ");
}
}
public void SelectSort(int a[]){
int i,j,min,temp;
for(i=0;i<a.length-1;i++){
min = i; //默认第一个元素是最小记录
for(j=i+1;j<a.length;j++){ //查找最小的记录
if(a[j]<a[min]){
min = j;
}
}
if(min != i){ //如果和默认最小元素的位置不相等,就交换位置
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
for(Integer num:a){
System.out.print(num+" ");
}
}
public static void main(String[] args) {
Sort sort = new Sort();
int a[] = {3,7,1,4,2,9,0};
System.out.print("冒泡排序的结果是:");
sort.BubleSort(a);
System.out.println();
System.out.print("选择排序的结果是:");
sort.SelectSort(a);
}
}