Java基础总结 - 数组排序之插入排序

Java基础总结 - 数组排序之插入排序
这篇文章只是把大学记的笔记整理到博客,方便自己查看,不保证权威性(•̀ᴗ•́)و ̑̑
import java.util.Arrays;
/**
 * 直接插入排序
 * 概念是,假设将数字插入一个有序数列,当array[0]一个数字默认有顺序,然后把array[1]比较然后插入,
 * 再把array[2]插入array[0]、array[1]有序数列,插入一个数字之前数组默认就是有序了。
 * 
 * @author CL-computer
 *
 */
public class InsertSort {
	public static void main(String[] args) {		
		int[] nums = {1,5,7,1,6,9,8,5};
		InsertSortMetohd(nums);
		System.out.println(Arrays.toString(nums));
	}

	public static void InsertSortMetohd(int[] nums) {
		
		for(int i = 0;i<nums.length;i++){
			for(int j=i;j>0;j--){
				if(nums[j-1]>nums[j]){
					int temp = 0;
					temp = nums[j];
					nums[j] = nums[j-1];
					nums[j-1] = temp;
				}else{
					break;
				}
			}
		}
	}
}
/**
 * 希尔排序:
 * 是一种压缩增量的排序算法
 * 这个增量现在大多数选择 数组长度的一半,但是这不是最好的。
 * 
 * 第一次使用数组长度一半进行跳跃的比较排序,
 * 第二次使用数组长度一半的一半,直到gap等于1时数组就有序了
 * 
 * 时间复杂度: n1.3 n n2
 * 空间复杂度: 1
 * 
 * @author CL-computer
 *
 */

public class ShellSort {
	public static void main(String[] args) {		
		int[] nums = {1,5,7,1,6,9,8,5};
		ShellSortMetohd(nums);
		System.out.println(Arrays.toString(nums));
	}

	public static void ShellSortMetohd(int[] nums) {
		for(int gap = nums.length/2;gap>0;gap/=2){
			for(int i =0;i<nums.length;i++){
				for(int j=i+gap;j<nums.length;j+=gap){
					
					if(nums[j]<nums[j-gap]){
						int temp = 0;
						temp = nums[j];
						nums[j] = nums[j-gap];
						nums[j-gap] = temp;
					}
					
				}
			}
		}
		
	}
	  
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章