Java学习笔记(23) Sorting

来源:互联网 发布:远程传输软件 编辑:程序博客网 时间:2024/06/05 19:24

23.1Introduction

The data to be sorted might be integers, doubles,characters, or objects.The Java API contains severaloverloaded sort methods for sorting primitive type values and objects in thejava.util.Arrays andjava.util.Collectionsclasses. For simplicity, this chapter assumes:

1. data to be sorted are integers,

2. data are stored in an array, and

3. data are sorted in ascending order.

The programs can be easily modified to sortother types of data, to sort in descending order, or to sort data in anArrayListor aLinkedList.


23.2Insertion Sort

The insertion-sort algorithm sorts a list of values byrepeatedly inserting a new element into a sorted sublist until the whole listis sorted.


LISTING23.1InsertionSort.java

1 public class InsertionSort {2 /** The method for sorting the numbers */3 public static void insertionSort(int[] list) {4 for (int i = 1; i < list.length; i++) {5 /** Insert list[i] into a sorted sublist list[0..i-1] so that6 list[0..i] is sorted. */7 int currentElement = list[i];8 int k;9 for (k = i - 1; k >= 0 && list[k] > currentElement; k--) {10 list[k + 1] = list[k];11 }1213 // Insert the current element into list[k + 1]14 list[k + 1] = currentElement;15}16 }17}

At the kth iteration, to insert an element into an array of sizek, it may takek comparisons to findthe insertion position, andkmoves to insert the element. LetT(n)denote the complexityfor insertion sort andcdenote the total number of other operations such asassignments and additional comparisons in each iteration. Thus,

Therefore, the complexity of the insertion sort algorithmis O(n2). Hence, the selection sort and insertion sort are of the same timecomplexity.


23.3 BubbleSort

Abubble sort sorts the array in multiple phases. Each pass successively swapsthe neighboring elements if the elements are not in order.

The bubble sort algorithm makes several passes throughthe array. On each pass, successive neighboring pairs are compared. If a pairis in decreasing order, its values are swapped; otherwise, the values remainunchanged. The technique is called a bubble sort or sinking sort, because thesmaller values gradually “bubble” their way to the top and the larger values sink to thebottom. After the first pass, the last element becomes the largest in thearray. After the second pass, the second-to-last element becomes the secondlargest in the array. This process is continued until all elements are sorted.

LISTING23.2Bubble SortAlgorithm

1 for (int k = 1; k < list.length; k++) {2 // Perform the kth pass3 for (int i = 0; i < list.length - k; i++) {4 if (list[i] > list[i + 1])5 swap list[i] with list[i + 1];6 }7 }

Note that if no swap takes place in a pass, there is noneed to perform the next pass, because all the elements are already sorted. Youcan use this property to improve the algorithm in Listing 23.2 as in Listing23.3.

LiSTING23.3ImprovedBubble Sort Algorithm

1 boolean needNextPass = true;2 for (int k = 1; k < list.length && needNextPass; k++) {3 // Array may be sorted and next pass not needed4 needNextPass = false;5 // Perform the kth pass6 for (int i = 0; i < list.length – k; i++) {7 if (list[i] > list[i + 1]) {8 swap list[i] with list[i + 1];9 needNextPass = true; // Next pass still needed10 }11 }12}

LISTING23.4BubbleSort.java

1 public class BubbleSort {2 /** Bubble sort method */3 public static void bubbleSort(int[] list) {4 boolean needNextPass = true;56 for (int k = 1; k < list.length && needNextPass; k++) {7 // Array may be sorted and next pass not needed8 needNextPass = false;9 for (int i = 0; i < list.length - k; i++) {10 if (list[i] > list[i + 1]) {11 // Swap list[i] with list[i + 1]12 int temp = list[i];13 list[i] = list[i + 1];14 list[i + 1] = temp;1516 needNextPass = true; // Next pass still needed17 }18 }19 }20 }2122 /** A test method */23 public static void main(String[] args) {24 int[] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};25 bubbleSort(list);26 for (int i = 0; i < list.length; i++)27 System.out.print(list[i] + " ");28 }29 }

 

-2 1 2 2 3 3 5 612 14

 

In the best case, the bubble sort algorithm needs justthe first pass to find that the array is already sorted—no next pass isneeded. Since the number of comparisons is n - 1 in the first pass, thebest-case time for a bubble sort is O(n).

In the worst case, the bubble sort algorithm requires n -1 passes. The first pass makes n - 1 



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 公司要求补税没钱补怎么办 公司补税补不起了怎么办 脚被石头砸肿了怎么办 砸到脚背肿了怎么办 小猫吃完饭抓地怎么办 耳机链接处断了怎么办 表链从表盘断了怎么办 龟头和皮分开了怎么办 微信买票被骗了怎么办 撞车了我的全责怎么办 蒙田包包里面不耐脏怎么办? 摩托车转向灯不会打怎么办 浓硫酸弄到脸上怎么办 钥匙被锁在家里怎么办 有奶宝宝吸不出来怎么办 奶涨宝宝吸不出来怎么办 高铁票未取误点怎么办 飞猪上12306占座失败怎么办? 新生儿肚脐还没有脱落发炎怎么办 蹲坑被纸巾堵了怎么办 老公有外遇老婆不想离婚怎么办 结婚十年妻子出轨该怎么办 初生儿眼睛多眼屎怎么办 被丝袜脚摩擦过瘾了怎么办 老公在卧室装摄像头怎么办 听了鬼故事害怕怎么办 看完鬼片害怕睡不着怎么办 晚上看了鬼片怎么办 说话不经过大脑考虑怎么办 我太受欢迎了怎么办动漫结局 狗胃不好总呕吐怎么办 比格犬晚上叫怎么办 玻尿酸隆鼻变宽了怎么办 打玻尿酸鼻子变宽怎么办 鼻炎的人感冒了怎么办 小孩上幼儿园反复感冒怎么办 3岁宝宝感冒鼻炎怎么办 鼻炎犯了鼻子不通气怎么办 食物呛到鼻子里怎么办 胃疼引起的焦虑怎么办 泰迪犬发生口腔亏痒怎么办?