您的位置:首页 > 编程语言 > Java开发

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

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

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 stub
int 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]+" ");
}

}

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