Sorting Algorithm - Selection Sort

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:

  1. The algorithm is straightforward and not very hard to implement.
  2. The space complexity is constant. This algorithm don’t need auxiliary space.

Cons:

  1. 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

  1. Why time complexity refers the worst time complexity?
  2. Why we say the space complexity is constant? We still use some space for declaring variable.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值