您的位置:首页 > 其它

排序算法1——(选择、插入、冒泡)

2016-05-14 22:59 309 查看

一.选择排序

算法复杂度:O(n^2) 

原理:对于给定的一组记录,经过第一轮比较后得到最小的记录,然后将该记录的位置与第一个记录的位置进行交换;接着对不包括以第一个记录的其他记录进行第二轮比较,得到最小的记录并与第二个纪录进行位置交换;重复该过程,直到进行比较的记录只有一个为止。

示例程序如下:

public class select {

public static void selectSort(int[] a){
int temp,flag;
int length = a.length;
for(int i=0;i<length;i++){
temp = a[i];
flag = i;
for(int j=i+1;j<length;j++){
if(a[j]<temp){
temp =a[j];
flag = j;
}
}
if(flag != i){
a[flag] = a[i];
a[i] = temp;
}
}
}

public static void main(String[] args){
int a[] = {5,4,9,8,7,6,0,1,3,2};
int len = a.length;
selectSort(a);
for(int i=0;i<len;i++){
System.out.println(a[i]+" ");
}
}
}

二.插入排序

算法复杂度:O(n^2) 

原理:对于给定的一组记录,初始时假设第一个记录自成一个有序序列,其余记录为无序序列。接着从第二个纪录开始,按照记录的大小将当前处理的记录插入到其之前的有序序列中,直至最后一个记录插入到有序序列中为止。

示例程序如下:

public class insert {
public static void insertSort(int[] a){
int j,temp,length = a.length;
if(a != null){
for(int i=1;i<length;i++){
temp = a[i];
j = i;
if(a[j-1]>temp){
while(j>=1&&a[j-1]>temp){
a[j] = a[j-1];
j--;
}
}
a[j] = temp;
}
}
}

public static void main(String[] args){
int a[] = {5,4,9,8,7,6,0,1,3,2};
int len = a.length;
insertSort(a);
for(int i=0;i<len;i++){
System.out.println(a[i]+" ");
}
}
}

三.冒泡排序

算法复杂度:O(n^2) 

原理:对于给定的n个记录,从第一个记录开始依次对相邻的两个记录进行比较,当前面的记录大于后面的记录时,交换位置,进行一轮比较和换位后,n个记录中的最大记录将位于第n位,然后对前(n-1)个记录进行第二轮比较;重复该过程直到进行比较的记录只剩下一个为止。

示例程序如下:

public class bubble {
public static void bubbleSort(int[] a){
int temp,length = a.length;
for(int i=0;i<length-1;i++){
for(int j=length-1;j>i;j--){
if(a[j]<a[j-1]){
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
}

public static void main(String[] args){
int a[] = {5,4,9,8,7,6,0,1,3,2};
int len = a.length;
bubbleSort(a);
for(int i=0;i<len;i++){
System.out.println(a[i]+" ");
}
}
}

冒泡排序优化:

当给定的待排序的记录中除少量关键字需要交换外,其他关键字均为正常顺序时,进行了大量多余比较(如{2,1,3,4,5,6,7,8,9})。我们可以通过增加一个标记变量flag来实现改进。

public static void bubbleSort(int[] a){
int temp,length = a.length;
boolean flag = true;                    //flag用来作为标记
for(int i=0;i<length-1 && flag;i++){    //若flag为true则退出循环
flag = false;                        //初始设为false
for(int j=length-1;j>i;j--){
if(a[j]<a[j-1]){
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
flag = true;                //如果有数据交换,则flag为true
}
}
if (flag == true)
break;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: