交换排序
1.冒泡排序
原理:双层循环,不断判断前后两个数的大小,交换位置。每次循环将一个最大或最小的数带到最前或最后。
要点:设计交换判断条件,提前结束以排好序的序列循环。
/* 冒泡排序 (上浮法)*/
public static void maopao(){
int temp;
int[] b={26,37,8,59,10,61,32,13,54,15};
print(b);
System.out.println();
for(int i=0;i<b.length;i++){
for(int j=1;j<b.length-i;j++){
if(b[j-1]>b[j]){
temp=b[j];
b[j]=b[j-1];
b[j-1]=temp;
}
}
}
print(b);
}
***********************************************
/* 排序法(下浮法)*/
public static void maopao1(){
int[] b={26,37,8,59,10,61,32,13,54,15};
int temp;
int i=0;
print(b);
System.out.println();
while(i<b.length-1){
for(int j=i+1;j<b.length;j++){
if(b[i]>b[j]){
temp=b[j];
b[j]=b[i];
b[i]=temp;
}
}
int j=i+1;
i++;
}
print(b);
}
<strong></strong>
<strong></strong><p align="left">【结果:】</p><p align="left"><span style="color:black;">26 37 8 59 10 61 32 13 54 15 </span></p><span style="color:black;">8 10 13 15 26 32 37 54 59 61</span>
<strong>2.快速排序</strong>是由东尼·霍尔所发展的一种排序算法 基本思想是:<span style="BACKGROUND: #d9d9d9">通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,</span>然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
/* 快速排序*/
public static void fastSort(){
int[] b={26,37,8,59,10,61,32,13,54,15};
print(b);
if(b.length>1){
quite(b,0,b.length-1);
}
print(b);
}
//控制排序范围
public static void quite(int[] b,int first,int last){
if(first<last){ //二分法排序,first=last
int centen=centen(b,first,last);
quite(b,first,centen-1); //左半部分进行排序
quite(b,centen+1,last); //有半部分进行排序
}
}
//从头到尾进行一次排序,返回中间的某个空位centen,左边全小于centen,右边全大于centen
static int index=0;
public static int centen(int[] a,int low,int high){
int temp;
temp=a[low];
while(low<high){ //两个指针相遇之前
if(low<high && a[high]>temp){
high--;
}
a[low]=a[high]; //此时low指的位置是重复的,在此之后,high的位置是重复的
if(low<high && a[low]<temp){
low++;
}
a[high]=a[low]; //在此之后,low的位置是重复的
}
a[low]=temp;
System.out.print("第"+(index++)+"遍:temp="+temp);
print(a);
return low;
}
【结果:】
快速排序前:
26 37 8 59 10 61 32 13 54 15
第0遍:temp=26
15 13 8 10 26 61 32 59 54 37
第1遍:temp=15
10 13 8 15 26 61 32 59 54 37
第2遍:temp=10
8 10 13 15 26 61 32 59 54 37
第3遍:temp=61
8 10 13 15 26 37 32 59 54 61
第4遍:temp=37
8 10 13 15 26 32 37 59 54 61
第5遍:temp=59
8 10 13 15 26 32 37 54 59 61
快速排序后:
8 10 13 15 26 32 37 54 59 61