Solution for exercise 1.2-1 in Introduction to Algorithms

Consider sorting n numbers stored in array A by first finding the smallest element of A and putting it in the first entry of another array B . Then find the second smallest element of A and put it in the second entry of B. Continue in this manner for the n elements of A. Write pseudocode for this algorithm, which is known as selection sort . Give the best-case and worst-case running times of selection sort in θ-notation.

/*
 * Sorting n numbers stored in array A by finding the smallest element of
 * unsorted part, and putting it in the end of sorted part.
 *
 * The best-case running times in θ-notation is θ(n^2).
 * The worst-case running times in θ-notation is θ(n^2).
 */
void Algorithms::selectionSort(int A[], int n) {
    int min;
   
    for (int i = 0; i < n; i++) {
        min = i;
        for (int j = i + 1; j < n; j++) {
            if (A[j] < A[min]) {
                min = j;
            }
        }
       
        if (min > i) {
            // switch A[i] and A[min]
            int temp = A[i];
            A[i] = A[min];
            A[min] = temp;
           
            // Alternative 1 for switching A[i] and A[min]
            // A[i] ^= A[min];
            // A[min] ^= A[i];
            // A[i] ^= A[min];
           
            // alternative 2 for switching A[i] and A[min]
            // A[i] += A[min];
            // A[min] = A[i] - A[min];
            // A[i] = A[i] - A[min];
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值