版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shytry/article/details/78987137
冒泡排序:较小的数值逐渐浮向顶部,较大的数值逐渐沉向底部。具体操作:根据下标比较其值,即,位置1数值和位置2数值比较,数值2>数值1则互换位置,否则继续比较位置2和位置3数值,依次后推。。。
代码如下:
/*初始数组元素*/ int [] arr= {1,2,3,4,5,6,7}; /*冒泡排序*/ for(int j=0;j<arr.length;j++){ for(int i=0;i<arr.length-j-1;i++){ if(arr[i]>arr[i+1]){ int x=arr[i]; arr[i]=arr[i+1]; arr[i+1]=x; } } } /*加强for循环输出结果*/ for (int y:arr) { System.out.print(y+" "); }归并排序:首先将数组不断分割,最终分割为1个数值,之后将每部分的数值相比较,再重组。
例如:2 9 5 4 8 1
第一次分割:2 9 5<--->4 8 1两部分
第二次分割:2 9<-> 5 4 8<-> 1
第三次分割:2 <-> 9<-> 5 4<-> 8<-> 1
组合:2 9->5 ---- 4 8->1
组合:2 5 9 ----1 4 8
组合:1 2 4 5 8 9
代码如下:
/*归并排序*/ /*分*/ public static void devide(int [] list){ /*list 前半部分*/ if(list.length==1) return; int [] size1=new int[list.length/2]; System.arraycopy(list,0,size1,0,size1.length); devide(size1); /*list 后半部分*/ int [] size2=new int[list.length/2]; System.arraycopy(list,list.length/2,size2,0,size2.length); devide(size2); int [] result=merge(size1,size2); System.arraycopy(result,0,list,0,result.length); } /*合*/ public static int[] merge(int [] list1,int [] list2){ int [] temp=new int[list1.length+list2.length]; int size1= 0; int size2= 0; int size3= 0; while(size1<list1.length&&size2<list2.length){ if(list1[size1]<list2[size2]){ temp[size3++]=list1[size1++]; }else temp[size3++]=list1[size2++]; } if(size1==list1.length) System.arraycopy(list2,size2,temp,size3,temp.length-size3); else System.arraycopy(list1,size1,temp,size3,temp.length-size3); return temp; }
快速排序:思路理解建议阅读-> http://developer.51cto.com/art/201403/430986.htm
代码如下:
/*---->快速排序<----*/ public static void quick(int[] list,int first,int low){ /*递归出口*/ if(low==0||first>low) return; int right=low; int left=first+1; int temp=list[first]; while(left<right){ while(list[right]>temp&&left<right) right--; while(list[left]<temp&&left<right) left++; if(left<right){ int tempx=list[right]; list[right]=list[left]; list[left]=tempx; } } /*互换标志---注意判断条件*/ if(list[right]<temp){ list[first]=list[right]; list[right]=temp; } quick(list,first,right-1); quick(list,right+1,low); }