java排序 内部排序 选择排序

package com.basic.sort;

public class BasicSort {
	public static void main(String argvs[]) {
		int test[] = {3,1,2,5,4,3};
		
//		choose s = new choose(test);
//		s.sort();
//		s.print();
		
		heap h = new heap(test);
		h.sort();
		h.print();
	}
}

/**
 * 选择排序:内部排序中的直接选择排序  时间复杂度O(n^2)
 */
class choose {
	private int[] array;
	
	public choose(int[] arr) {
		this.array = arr;
	}
	
	public void sort() {
		for(int i = 0; i < this.array.length; i++) {
			int lowindex = i;
			int tmp = this.array[i];
			for(int j = i + 1; j < this.array.length; j++) {
				if (tmp > this.array[j]) {
					tmp = this.array[j];
					lowindex = j;
				}
			}
			this.array[lowindex] = this.array[i];
			this.array[i] = tmp;
		}
	}
	
	public void print() {
		for (int i = 0; i < this.array.length; i++) {
			System.out.println(this.array[i]);
		}
	}
}


/**
 * 堆排序:内部排序中的选择排序  时间复杂度O(nLogn)
 */
class heap {
	private int[] array;
	
	public heap(int[] arr) {
		this.array = arr;
	}
	
	public void sort() {
		for(int i = 0; i < this.array.length-1; i++) {
			buildmaxheap(this.array, this.array.length-1-i);
			swap(this.array, 0, this.array.length-1-i);
		}
	}
	
	private void buildmaxheap(int[] arr, int lastindex) {
		for (int i = (lastindex-1)/2; i >= 0; i--) {
			int k = i;
			//左孩子存在则不断比较
			while(k*2+1 <= lastindex) {
				//获取当前节点的左孩子的数组索引
				int big = 2 * k + 1;
				if (big < lastindex) {
					//若右孩子的值大于左孩子的值则选择右孩子来和当前节点交互
					if (arr[big] < arr[big+1]) {
						big++;
					}
				}
				
				if (arr[k] < arr[big]) {
					swap(arr, k, big);
					//保存需要继续比较的当前节点,比如在根节点调整的情况下,孩子的孩子可能也需要再调整
					k = big;
				} else {
					break;
				}
			}
		}
	}
	
	private void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}
	
	public void print() {
		for (int i = 0; i < this.array.length; i++) {
			System.out.println(this.array[i]);
		}
	}
}

你可能感兴趣的:(java排序 内部排序 选择排序)