排序與堆疊 (Sorting and Searching)
常見的排序演算法
泡泡排序法 (Bubble Sort)
Bubble Sort Implementation
1 |
|
- Time Complexity: $O(n^2)$
選擇排序法 (Selection Sort)
Selection Sort Implementation
1 |
|
- Time Complexity: $O(n^2)$
合併排序法 (Merge Sort)
- Time Complexity: $O(nlog(n))$
Merge Sort Implementation
1 |
|
快速排序法 (Quick Sort)
- Time Complexity: $O(nlog(n))$
- Worst Time Complexity: $O(n^2)$
使用分治法(Divide and Conquer)的概念。
1 | // 原始資料 |
Quick Sort Implementation (version 1)
1 |
|
基數排序 (Radix Sort)
- Time Complexity: $O(nk)$
基數排序利用整數有限位元這個條件,迭代數字的每一位數,對每一位數分群。
1 | // 原始資料 |
1 |
|
搜尋演算法
二元搜尋法 (Binary Search)
面試題目
10.1 Sorted Merge
You are given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
(Hints.)
由陣列後面插入比較好,因為有空位。
1 |
|
10.2 Group Anagrams
Write a method to sort an array of strings so that all the anagrams are next to each other.
anagrams (易位構詞遊戲): 是將組成一個詞或短句的字母重新排列順序,所有字母的都被使用一次,構造出一些新的詞或短句。
example:
- “earth” <—> “heart”
- “eleven plus two” <—> “twelve plus one”
1 |
|
10.3 Search in Rotated Array
Given a sorted array of n integers that has been rotated an unknown number of times, write code to find an element in the array. You may assume that the array was originally sorted in increasing order.
1 | [1,2,3,4,5,6] |
思路:
- 從小至大排列的旋轉,至少有一側排序是對的。
- 若目標在排序正確的一側,則binary search。
若目標在另一側,則繼續從另一側搜尋。
1 |
|
10.4 Sorted Search, No Size
You are given an array like data structure Listy which lacks a size method. It does, however, have an elementAt(i) method that returns the element at index i in 0(1) time. If i is beyond the bounds of the data structure, it returns -1. (For this reason, the data structure only supports positive integers.) Given a Listy which contains sorted, positive integers, find the index at which an element x occurs. If x occurs multiple times, you may return any index.
思路:
- 先找出Listy大概的長度 (利用指數加大的方式)。
- 接著使用二元搜尋。
1 |
|
10.5 Sparse Search
Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.
思路:
先找中點附近,不為空的字串。
1 |
|
10.6 Sort Big File
Imagine you have a 20 GB file with one string per line. Explain how you would sort the file.
因限制了20GB的大小,表示不能單純把全部資料帶進記憶體處理。
我們可以將檔案分塊,每一塊獨立排序,存進檔案。
待所有區塊排序後,
再將區塊一塊一塊合併(可透過每次存取第一行的合併排序),
最終產生完全排序的檔案。
此演算法稱為外排序 (external sort)。
(Reference.)
ʕ •ᴥ•ʔ:排序演算法還有很多,之後有時間再來補充吧!