几个排序算法
1.快速排序
1 public class quicksorts { 2 public static List<Integer> quicks(List<Integer> nums) 3 { 4 if(nums.size()<2) 5 return nums; 6 final List<Integer> lower=new ArrayList<Integer>(); 7 final List<Integer> higher=new ArrayList<Integer>(); 8 final int pivot=nums.get(0); 9 for(int i=1;i<nums.size();i++) 10 { 11 if(nums.get(i)>pivot) 12 higher.add(nums.get(i)); 13 else lower.add(nums.get(i)); 14 } 15 final List<Integer> con=quicks(lower); 16 con.add(pivot); 17 con.addAll(quicks(higher)); 18 return con; 19 } 20 }
2.插入排序
1 public class insertsorts { 2 public static List<Integer> ins(final List<Integer> nums) 3 { 4 List<Integer> insertsorted=new LinkedList<>(); 5 ori:for(int num:nums) 6 { 7 for(int i=0;i<insertsorted.size();i++) 8 { 9 if(num<insertsorted.get(i)) 10 {insertsorted.add(i,num); 11 continue ori;} 12 } 13 insertsorted.add(insertsorted.size(),num); 14 } 15 return insertsorted; 16 } 17 }
3.冒泡排序
1 public class bubblesort { 2 public static void bubblesorts(int[] nums) 3 { 4 boolean flag; 5 do 6 { 7 flag=false; 8 for(int i=0;i<nums.length-1;i++) 9 { 10 if(nums[i]>nums[i+1]) 11 { 12 int temp=nums[i+1]; 13 nums[i+1]=nums[i]; 14 nums[i]=temp; 15 flag=true;} 16 } 17 }while (flag); 18 for(int j=0;j<nums.length;j++) 19 System.out.print(nums[j]+" "); 20 } 21 }
4.归并排序
public class mergesort { public static void sort1(int[] a,int low, int high, int[] temp) { if(low<high) { int mid=(low+high)/2; sort1(a,low,mid,temp); sort1(a,mid+1,high,temp); merge(a,low,mid,high,temp); } } public static void merge(int[] a,int low, int mid,int high,int[] temp) { int i=low; int j=mid+1; int k=0; while(i<=mid&&j<=high) { if(a[i]<a[j]) temp[k++]=a[i++]; else temp[k++]=a[j++]; } while(i<=mid) { temp[k++]=a[i++]; } while(j<=high) { temp[k++]=a[j++]; } for(i=0; i<k; i++){ a[low+i] = temp[i]; } } }