常见排序算法
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(); } }
相关文章推荐
- 常见排序算法对比二(C++实现)
- 几种常见排序算法的C语言实现
- 算法学习一之常见的七大排序算法
- 常见排序算法的Java实现(1)——冒泡排序
- 常见排序算法(js实现)
- 常见排序算法
- 复习----常见的排序算法
- JavaScript版几种常见排序算法
- C语言中冒泡法、选择法、插入法三种常见排序算法分析
- 常见排序算法性能测试
- 关于常见排序算法的稳定性分析和结论
- 常见排序算法原理及代码实现
- [笔试]几种常见的排序算法对比
- 常见排序算法的实现
- 8个常见排序算法
- 【数据结构与算法】-常见排序算法总结
- 常见排序算法C++实现(冒泡,直接插入,希尔,堆,归并,简单选择,快排)
- java中的一些常见排序算法
- 【转】常见排序算法分析及java实现
- 用Java实现几种常见的排序算法