[Java] Selection Sort Algorithm

[Java] Selection Sort Algorithm

Time complexity of Selection Sort Algorithm in best case , worst case and average are all O(n^2) and need O(1) extra space. Selection sort can be implemented in stable sort or not.


How to implemented by Java? please follow below code:

public class SelectionSort {
    public static int[] selectionSort(int[] inputArray) {
        int[] arr = inputArray.clone();
        int len = arr.length; // get the length of array
        for (int i = 0; i < len - 1; i++) {
            int temp = i; // store the index
            for (int k = i + 1; k < len; k++) { if (arr[temp] > arr[k])
                temp = k;
            }
            if (i != temp) { // if index is the same, then swap elements of array
                int buffer = arr[i];
                arr[i] = arr[temp];
                arr[temp] = buffer;
            }
        }
        return arr;
    }
    public static void main(String[] args) {
        int x[] = { 12, 14, 29, 20, 22, 39, 41, 52, 1, 7, 10, 101, 93 };
        int y[] = selectionSort(x);
        for (int i = 0; i < y.length; i++) {
            int a = y[i];

            System.out.print(a + ",");
        }
    }
}
(Visited 18 times, 1 visits today)

2 thoughts on “[Java] Selection Sort Algorithm

    1. Hi~您說我的轉換跑道是指開始寫iOS跟Android嗎?
      我自己覺得寫手持裝置有趣多了,未來應該也會繼續朝這方向走。

      您的工作是開車店?還是?我看您的blog上也有分享一些程式,似乎您也是工程師?

Comments are closed.

Comments are closed.