插入排序和冒泡排序

1、插入排序:插入是比较简单的一种排序方法,基本思想就是把数据分组两段,一部分是有序,另一部分是待排序的。把有序的数据不断的加大到全数组完成排序。

从左到右将有序数组逐渐增大。

[java]  view plain copy
  1. public class Sort {  
  2.     public void insertSort(int[] arrays) {  
  3.         for (int i = 0; i < arrays.length; i++) {  
  4.             for (int j = i; j > 0; j--) {  
  5.                 if (j == 0)  
  6.                     continue;  
  7.                 if (arrays[j] < arrays[j - 1]) {  
  8.                     sweep(arrays, j, j-1);  
  9.                 }  
  10.             }  
  11.         }  
  12.     }  
  13.     //交换两个数的位置  
  14.     private void sweep(int[] arrays,int a,int b){  
  15.         int temp=arrays[a];  
  16.         arrays[a]=arrays[b];  
  17.         arrays[b]=temp;  
  18.     }  
  19.     public static void main(String[] args) {  
  20.         int[] a = { 493865,12,45,5 };  
  21.         for (int i : a) {  
  22.             System.out.print(i+" ");  
  23.         }  
  24.         System.out.println();  
  25.         Sort sort=new Sort();  
  26.         sort.insertSort(a);  
  27.         for (int i : a) {  
  28.             System.out.print(i+" ");  
  29.         }  
  30.     }  
  31. }  

2、冒泡排序:把数组中比较大的数不断的冒在前面。一直冒完整个数据就完成排序。

[java]  view plain copy
  1. public class Sort {  
  2.     public void bubbleSort(int[] arrays) {  
  3.         for(int i=0;i<arrays.length;i++){  
  4.             for(int j=i+1;j<arrays.length;j++){  
  5.                 if(arrays[i]>arrays[j]){  
  6.                     sweep(arrays, i, j);  
  7.                 }  
  8.             }  
  9.         }  
  10.     }  
  11.     //交换两个数的位置  
  12.     private void sweep(int[] arrays,int a,int b){  
  13.         int temp=arrays[a];  
  14.         arrays[a]=arrays[b];  
  15.         arrays[b]=temp;  
  16.     }  
  17.     public static void main(String[] args) {  
  18.         int[] a = { 493865,12,45,5 };  
  19.         for (int i : a) {  
  20.             System.out.print(i+" ");  
  21.         }  
  22.         System.out.println();  
  23.         Sort sort=new Sort();  
  24.         sort.bubbleSort(a);  
  25.         for (int i : a) {  
  26.             System.out.print(i+" ");  
  27.         }  
  28.     }  
  29. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值