排序算法--选择排序(简单选择排序、堆排序)java实现

来源:互联网 发布:网络大学怎么报名 秋季 编辑:程序博客网 时间:2024/05/22 15:58
每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。选择排序是不稳定的排序方法,包括简单选择排序和堆排序
package sortAlgorithms;/* *  * @author x@j * @date 2013-10-01 * @content SelectSort * 选择排序(Selection Sort)的基本思想是: * 每一趟从待排序的记录中选出关键字最小的记录, * 顺序放在已排好序的子文件的最后,直到全部记录排序完毕 * 直接选择排序 * */public class SelectSort<E extends Comparable<E>> extends Sort<E> {public static void main(String[] args) {SelectSort<Integer> is=new SelectSort<Integer>();Integer[] a={49,38,65,97,76,13,27,49};is.sort(a);}@Overridepublic void sort(E[] a, int p, int q) {System.out.print("Select sort初始序列为");        printArray(a);for(int i=p;i<q;i++){int position=i;for(int j=i+1;j<a.length;j++){if(a[j].compareTo(a[position])<0){position=j;}    }swap(a,i,position);System.out.print("第 "+i+ "趟排序结果为");printArray(a); }     }}/*Select sort初始序列为 49 38 65 97 76 13 27 49第 0趟排序结果为 13 38 65 97 76 49 27 49第 1趟排序结果为 13 27 65 97 76 49 38 49第 2趟排序结果为 13 27 38 97 76 49 65 49第 3趟排序结果为 13 27 38 49 76 97 65 49第 4趟排序结果为 13 27 38 49 49 97 65 76第 5趟排序结果为 13 27 38 49 49 65 97 76第 6趟排序结果为 13 27 38 49 49 65 76 97*/

package sortAlgorithms;/* * @author x@j * @date 2013-10-01 * @content HeapSort * 堆排序(Heap sort)是指利用堆积树(堆)这种数据结构所设计的一种排序算法,可以利用数组的特点快速定位指定索引的元素。 */public class HeapSort<E extends Comparable<E>> extends Sort<E> {public static void main(String[] args) {HeapSort<Integer> is=new HeapSort<Integer>();Integer[] a={49,38,65,97,76,13,27,49};is.sort(a);}public int parent(int i){return (i-1)/2;}public int left(int i){return 2*i+1;}public int right(int i){return 2*i+2;}public void maxHeapify(E[] a,int i,int heapSize){int l=left(i);int r=right(i);int largest=i;if(l<=heapSize&&a[l].compareTo(a[i])>0){largest=l;}if(r<=heapSize&&a[r].compareTo(a[largest])>0){largest=r;}if(largest!=i){System.out.println("largest="+largest+"i="+i);swap(a,largest,i);maxHeapify(a,largest,heapSize);}}public void buildMaxHeap(E[] a){for(int i=a.length/2-1;i>=0;i--){maxHeapify(a,i,a.length-1);}}@Overridepublic void sort(E[] a, int p, int q) {printArray(a);buildMaxHeap(a);printArray(a);int heapSize=q-p;for(int i=q;i>=1;i--){swap(a,0,i);heapSize--;maxHeapify(a,0,heapSize);printArray(a);}}}/* 49 38 65 97 76 13 27 49largest=3i=1largest=7i=3largest=1i=0largest=4i=1 97 76 65 49 49 13 27 38largest=1i=0largest=3i=1 76 49 65 38 49 13 27 97largest=2i=0 65 49 27 38 49 13 76 97largest=1i=0largest=4i=1 49 49 27 38 13 65 76 97largest=1i=0largest=3i=1 49 38 27 13 49 65 76 97largest=1i=0 38 13 27 49 49 65 76 97 27 13 38 49 49 65 76 97 13 27 38 49 49 65 76 97)*/

原创粉丝点击