选择排序算法

时间:2016-05-01 17:57:04

标签: algorithm

如果我们重复选择子数组中最大的项目而不是最小的项目,我们必须对选择排序算法做出哪些更改?

1 个答案:

答案 0 :(得分:0)

你必须向后遍历数组。此外,最大元素应在(0,j)范围内找到。 这是来自维基百科文章的修改后的代码:

/* a[0] to a[n-1] is the array to sort */
int i,j;

/* iterate backwards the position through the entire array */
/*   (could do j > 0 because single element is also min element) */
for (j = n-1; j > 0; j--) {
    /* find the max element in the unsorted a[0 .. j] */

    /* assume the max is the first element */
    int iMax = 0;
    /* test against elements before j to find the largest */
    for ( i = 0; i <= j; i++) {
        /* if this element is greater, then it is the new minimum */
        if (a[i] > a[iMax]) {
            /* found new max; remember its index */
            iMax = i;
        }
    }

    if(iMax != j) {
        swap(a[j], a[iMax]);
    }
}