Selection Sort
Author: /罘憂請赱幵
Last Edit: 2019/7/27
Overview
Sorting algorithm is used to sort a collection of data in a given order. A collection of data can be an array, list and so on. Given order means that the algorithm won’t necessarily need to sort the data based on value, it can be used to sort the data based on other order, like date. There are many different sorting algorithm, they have their advantages and disadvantages. It depends on the use case to decide which algorithm to be used. The efficiency of sorting algorithm is judged by time complexity and space complexity. In this blog, we will focus on selection sort and its time/space complexity.
For simplicity, we will narrow the scope to sort the array in ascending order. The high level idea of selection sort is that it will select the minimum element in the current array, and put it in the right position. Then it will do the same thing in the rest of the array until all elements have been sorted. The time complexity is O(n^2) and space complexity is O(1). The Pros and Cons of selection sort is listed as follows:
Pros:
- The algorithm is straightforward and not very hard to implement.
- The space complexity is constant. This algorithm don’t need auxiliary space.
Cons:
- The time complexity is high in this algorithm.
Detail
Code implementation:
public class SelectionSort {
public static int[] sort(int[] array) {
if (array == null || array.length == 0) {
return new int[0];
}
for (int i = 0; i < array.length - 1; i++) {
int global_min = i;
for (int j = i + 1; j < array.length; j++) {
if(array[global_min] > array[j]) {
global_min = j;
}
}
swap(array, i, global_min);
}
return array;
}
private static void swap(int[] array, int i, int j) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
Question
- Why time complexity refers the worst time complexity?
- Why we say the space complexity is constant? We still use some space for declaring variable.