您的位置:首页 > 其它

常见排序算法

2012-11-12 11:36 106 查看
public class AllSort {
private int[] a;
private int index;

public AllSort(int n){
a = new int
;
index = 0;
}

public void insert(int value){
a[index++] = value;
}

public int size(){
return index--;
}
/**
* 冒泡排序
*/
public void bubSort(){
int temp;
for(int i=index-1; i>0; i--){
for(int j=0; j<i; j++){
if(a[j]>a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
/**
* 选择排序
*/
public void selSort(){
int k,temp;
for(int i=0; i<index-1; i++){
k = i;
for(int j=i+1; j<index; j++)
if(a[k]>a[j])
k = j;
if(k!=i){
temp = a[k];
a[k] = a[i];
a[i] = temp;
}
}
}

/**
* 插入排序
*/
public void inSort(){
for(int i=1; i<index; i++){
int temp = a[i];
int j = i;
while(j>0 && a[j-1]>temp){
a[j] = a[j-1];
j--;
}
a[j] = temp;
}
}

/**
* 希尔排序
*/
public void shellSort(){
int i,j,temp,h=1;
while(h<=index/3)
h = h*3+1;
while(h>0){
for(i=h; i<index; i++){
temp = a[i];
j = i;
while(j>h-1 && a[j-h]>=temp){
a[j] = a[j-h];
j -= h;
}
a[j] = temp;
}
h = (h-1)/3;
}
}

/**
* 快速排序
*/
public void quickSort(){
recQuickSort(0,index-1);
}

public void recQuickSort(int left,int right){
if(right-left<=0)
return;
else{
int pivot = a[right];
int partition = partitionIt(left,right,pivot);
recQuickSort(left,partition-1);
recQuickSort(partition+1,right);
}
}

public int partitionIt(int left,int right,int pivot){
int leftPtr = left - 1;
int rightPtr = right;
while(true){
while(a[++leftPtr]<pivot) ;
while(rightPtr>0 && a[--rightPtr]>pivot) ;
if(leftPtr >= rightPtr)
break;
else
swap(leftPtr,rightPtr);
}
swap(leftPtr,right);
return leftPtr;
}

public void swap(int x,int y){
int temp = a[x];
a[x] = a[y];
a[y] = temp;
}

public void display(){
for(int i=0; i<index; i++)
System.out.print(a[i]+" ");
System.out.println();
}

public static void main(String[] args) {
AllSort as = new AllSort(10);
Random r = new Random();
for(int i=0; i<10; i++)
as.insert(r.nextInt(10));
System.out.println("数据原序列:");
as.display();
System.out.println("冒泡排序后序列:");
as.bubSort();
as.display();
System.out.println("选择排序后序列:");
as.selSort();
as.display();
System.out.println("插入排序后序列:");
as.inSort();
as.display();
System.out.println("希尔排序后序列:");
as.shellSort();
as.display();
System.out.println("快速排序后序列:");
as.quickSort();
as.display();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: