插入式排序法——插入排序法
插入排序(InsertionSortion)的基本思想是:把n个待排序的元素看成一个有序表和一个无序表,开始有序表只包含一个元素,无序表中包含n-1个元素,排序过程中每次从无序表中取出第一个元素,把它的排序码依次与有序表元素的排序码进行比较,将它插入到有序表中的适当位置,使之成为新的有序表。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
public
class
Demo{
public
static
void
main(
String
[]args){
int
[]arr={
1
,
3
,
5
,
7
,
9
,
2
,
4
,
6
,
8
,
0
};
InsertSort
is
=
new
InsertSort();
is
.sort(arr);
for
(
int
i=
0
;i<arr.length;i++)
{
System.out.print(arr[i]+
""
);
}
}
}
class
InsertSort
{
//插入排序法
public
void
sort(
int
arr[])
{
for
(
int
i=
1
;i<arr.length;i++)
{
int
insertVal=arr[i];
//insertValue准备和前一个数比较
int
index=i-
1
;
while
(index>=
0
&&insertVal<arr[index])
{
//将把arr[index]向后移动
arr[index+
1
]=arr[index];
//让index向前移动一位
index--;
}
//将insertValue插入到适当位置
arr[index+
1
]=insertVal;
}
}
}
|
/*
* D. Shell 最初的算法。
*/
intshellsortSh(intp[],intn)
{
intop = 0;
inth,i,j,temp;
for(h = n/2; h > 0; h = h/2) {
for(i = h; i < n; i++) {
temp =p[i];
for(j = i-h; j >= 0 && p[j] > temp; j -= h) {
p[j+h] = p[j];
op++;
}
p[j+h] = temp;
op++;
}
}
returnop;
}
说来感到惭愧,昨天看别人的博客上面一一讲了一些算法,其实这些算法在大学都学过,不过几乎全部忘记了。虽然现在做java上层开发基本上用不到算法,但是还是感觉算法是一种思想,是一种灵魂,所以又不仅翻开了严蔚敏老师的数据结构,一个一个把以前忘记的算法实现一遍。
快速排序的基本思想:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。
先看一下这幅图:
把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。
- publicintgetMiddle(Integer[]list,intlow,inthigh){
- inttmp=list[low];//数组的第一个作为中轴
- while(low<high){
- while(low<high&&list[high]>tmp){
- high--;
- }
- list[low]=list[high];//比中轴小的记录移到低端
- while(low<high&&list[low]<tmp){
- low++;
- }
- list[high]=list[low];//比中轴大的记录移到高端
- }
- list[low]=tmp;//中轴记录到尾
- returnlow;//返回中轴的位置
- }
递归形式的分治排序算法:
- publicvoid_quickSort(Integer[]list,intlow,inthigh){
- if(low<high){
- intmiddle=getMiddle(list,low,high);//将list数组进行一分为二
- _quickSort(list,low,middle-1);//对低字表进行递归排序
- _quickSort(list,middle+1,high);//对高字表进行递归排序
- }
- }
- publicvoidquick(Integer[]str){
- if(str.length>0){//查看数组是否为空
- _quickSort(str,0,str.length-1);
- }
- }
编写测试方法:
- publicclassTestMain{
- /**
- *@paramargs
- */
- publicstaticvoidmain(String[]args){
- //TODOAuto-generatedmethodstub
- Integer[]list={34,3,53,2,23,7,14,10};
- QuicSortqs=newQuicSort();
- qs.quick(list);
- for(inti=0;i<list.length;i++){
- System.out.print(list[i]+"");
- }
- System.out.println();
- }
- }
2 3 7 10 14 23 34 53
这样就排序好了,快速排序是对冒泡排序的一种改进,平均时间复杂度是O(nlogn)。
快排序:http://blog.youkuaiyun.com/wangkuifeng0118/article/details/7286332