c/c++语言开发共享插入排序

插入排序的基本思想:每次将一个待排序的元素按其关键字大小插入到前面已经排好的子序表中的适当位置,直到全部元素插入完成为止。本次介绍直接插入排序,折半插入排序和希尔排序。 1 直接插入排序 直接插入排序(Straight Insertion Sort)的基本思想是:把n个待排序的元素看成为一个有序表和 …


插入排序

从第二个数起,与前面的数依次比较如果比前面的数小就交换,直到第二个数前面的数字顺序为从小到大为止,然后从第三个数重复以上过程,第四个、第五个…
模拟过程
例:对3 8 1 5 4 6 2 9 排序过程
3 8 1 5 4 6 2 9
3 8 1 5 4 6 2 9
3 1 8 5 4 6 2 9
1 3 8 5 4 6 2 9
1 3 5 8 4 6 2 9
1 3 5 8 4 6 2 9
1 3 5 8 4 6 2 9
1 3 5 4 8 6 2 9
1 3 4 5 8 6 2 9
1 3 4 5 8 6 2 9
1 3 4 5 8 6 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 8 2 9
1 3 4 5 6 2 8 9
1 3 4 5 2 6 8 9
1 3 4 2 5 6 8 9
1 3 2 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
1 2 3 4 5 6 8 9
代码实现

public class InsertSort { 	private int []arr; 	private int num; 	public static void main(String[] args) { 		InsertSort op=new InsertSort(); 		op.arr=new int[8]; 		op.insert(3); 		op.insert(8); 		op.insert(1); 		op.insert(5); 		op.insert(4); 		op.insert(6); 		op.insert(2); 		op.insert(9); 		op.sort();         op.display(); 	} 	public void insert(int a) { 		arr[num]=a; 		num++; 	} 	public void sort() { 		for(int i=1;i<num;i++) { 			int in=i; 			for(int j=i-1;j>=0;j--) { 				if(arr[in]<arr[j]) { 					swap(in,j); 					in=j; 				} 			} 		} 	} 	public void swap(int a,int b) { 		int temp; 		temp=arr[a]; 		arr[a]=arr[b]; 		arr[b]=temp; 	} 	public void display() { 		for(int i=0;i<num;i++) { 			System.out.println(arr[i]); 		} 	} }  

c/c++开发分享插入排序地址:https://blog.csdn.net/weixin_43813139/article/details/107593851

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/601596.html

(0)
上一篇 2021年5月10日
下一篇 2021年5月10日

精彩推荐