java实现常见的排序(冒泡、插入、选择、快排)

来源:互联网 发布:php.ini 编码设置 编辑:程序博客网 时间:2024/06/06 15:44

最近正在找实习 发现大公司第一轮的笔试都是没有重点 考的很广也很基础 其中数据结构的比重很大 我顺便练了练 把这些代码贴出来 放在这里以后也能用的上

ps:每个代码都写成一个class然后里面也有一个比较排序速度的main方法,有一个直观的排序效率展示

1 冒泡排序

package com.sort.implement;//冒泡排序public class BubbleSort {public BubbleSort(int[] a) {for(int i = 0; i< a.length-1;i++){for(int j = 0; j<a.length-i-1;j++){if(a[j]>a[j+1]){int temp = a[j];a[j]=a[j+1];a[j+1]=temp;}}}}public static void main(String[] args) {int []a = new int[]{5,4,3,2,1};//int []b = new int[]{26,53,48,11,13,48,32,15};double timer = System.nanoTime();BubbleSort s= new BubbleSort(a);//计算用时 ,下同System.out.println(System.nanoTime()-timer);for(int i = 0 ; i < a.length;i++){System.out.print(a[i]+" ");}}}

2 插入排序


package com.sort.implement;//插入排序public class InsertSort {public InsertSort(int []a){for(int i = 1;i < a.length;i++){int temp = a[i];int j = i-1; while(j>=0&&a[j]>temp){a[j+1] = a[j];j--;}a[j+1] = temp;}}public static void main(String[] args) {int []a = new int[]{5,4,3,2,1};double timer = System.nanoTime();InsertSort i1 = new InsertSort(a);System.out.println(System.nanoTime()-timer);for(int i = 0 ; i < a.length;i++){System.out.print(a[i]+" ");}}}

3 选择排序

package com.sort.implement;//选择排序public class SelectSort {private  SelectSort(int [] a) {// TODO Auto-generated method stubint len = a.length;for(int i = 0 ; i < len-1 ; i++){for(int j = i+1 ; j<len ;j++){if(a[i]>a[j]){int temp= a[i];a[i]=a[j];a[j]=temp;}}}}public static void main(String[] args) {int a[] = new int[]{5,4,3,2,1};double timer = System.nanoTime();SelectSort s = new SelectSort(a);System.out.println(System.nanoTime()-timer);for(int i = 0 ; i < a.length;i++){System.out.print(a[i]+" ");}}}


4 快速排序


package com.sort.implement;//快速排序public class QuickSort {public QuickSort(int []a,int low,int high ){int i=low;int j=high;int keyValue=a[i];while(i<j){int temp=0;while(i<j&&a[j]>=keyValue){j=j-1;}temp=a[j];a[j]=a[i];a[i]=temp;while(i<j&&a[i]<=keyValue){i=i+1;}temp=a[j];a[j]=a[i];a[i]=temp;}a[i]=keyValue;if(low<i-1){new QuickSort(a,low,i-1);}if(high>i+1){new QuickSort(a,i+1,high);}}public static void main(String[] args) {int a[] = new int[]{5,4,3,2,1};double timer = System.nanoTime();System.out.println(System.nanoTime()-timer);QuickSort i1 = new QuickSort(a,0,a.length-1);for(int i = 0 ; i < a.length;i++){System.out.print(a[i]+" ");}}}


原创粉丝点击