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

Java几种简单的排序源代码

2014-09-28 17:35 513 查看
package com.sort.test;

public class SortTest {

public static void main(String[] args) {
int a[]={1,4,7,2,5,8,3,6,9};
SortTest st=new SortTest();
st.show(a);
st.heapSort(a);
st.show(a);
}

//冒泡排序
public void BubbleSort(int t[]){
int temp;
for(int i=0;i<t.length;i++){
for(int j=0;j<t.length-i-1;j++){
if(t[j]>t[j+1]){
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}
}
}
}

//选择排序
public void selectSort(int t[]){
int len=t.length;
int MaxIndex=0;
for(int j=len;j>0;j--){
for(int i=0;i<j;i++){
if(t[i]>t[MaxIndex]){
MaxIndex=i;
}
}
swap(t,MaxIndex,j-1);
MaxIndex=0;
}
show(t);
}

public void swap(int t[],int a,int b){
int temp;
temp=t[a];
t[a]=t[b];
t[b]=temp;
}

//插入排序
public void InsertSort(int t[]){
int next;
int j;
for(int i=1;i<t.length;i++){
next=t[i];
j=i;
while(j>0&&next<t[j-1]){
t[j]=t[j-1];
j--;
}
t[j]=next;
}
show(t);
}

public int getPosition(int a[],int L,int R){
int temp=a[L];
while(L<R){
while(a[R]>=temp&&L<R){
R--;
}
if(L<R){
a[L]=a[R];
L++;
}
while(a[L]<=temp&&L<R){
L++;
}
if(L<R){
a[R]=a[L];
R--;
}
}
a[L]=temp;
return L;
}

//快速排序
public void quickSort(int a[],int start,int end){
if(start<end){
int i=getPosition(a,start,end);
quickSort(a,start,i);
quickSort(a,i+1,end);
}
}

//堆排序
public void heapSort(int a[]){
int len=a.length;
for(int i=len;i>0;i--){
buildHeap(a,i);
swap(a,0,i-1);
}
}

public void buildHeap(int a[],int len){
for(int i=len/2-1;i>=0;i--){
heap(a,i,len);
}
}

public void heap(int a[],int i,int len){
int left=i*2+1;
int right=i*2+2;
int largeIndex=0;
int temp = a[i];
if(left<len&&a[left]>a[i]){
largeIndex=left;
temp=a[left];
}else{
largeIndex=i;
}
if(right<len&&a[right]>temp){
largeIndex=right;
}
if(largeIndex!=i){
swap(a,largeIndex,i);
}

}

public static void show(int t[]){
for(int i=0;i<t.length;i++){
System.out.print(t[i]+" ,");
}
System.out.println("");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法 排序