zoukankan      html  css  js  c++  java
  • 选择排序(Selection Sort)

    选择排序就是在选择数组元素上做文章,关键是如何选择?选择的标准是什么?选择之后放在哪?所有这些都是选择排序的问题。

    选择排序算法中,通常会有以下操作:

    • 从数组第一个元素开始。
    • 遍历整个数组,找到最小的元素。
    • 将最小的元素与数组第一个元素交换。
    • 从第二个元素开始重复上述步骤。

    看一个例子:

    Selection Sort

    可以看到,一开始的数组是乱序的,红色的方块代表排好序的元素,蓝色的代表未排序的元素。

    • 从元素7开始,扫描后面的元素,找到最小的值。
    • 1是最小的元素,将1与7交换。
    • 从第二个元素开始,也就是4,扫描后面的元素找到最小值。
    • 将找到的最小值2与4交换位置。
    • 相似的,交换4和5。
    • 继续进行上述步骤,直到数组排序完成。

    相应的算法实现:

    #include<stdio.h>
     
    // function to swap two integers
    void swap(int *x, int *y)
    {
        int temp = *x;
        *x = *y;
        *y = temp;
    }
     
    //defining a function to perform selection sort on array arr[] of given size
    void selectionSort(int arr[], int size)
    {
        int i,j;
     
        for(i=0;i<size;i++)
        {
            //a variable to store the position with minimum element
            int min_pos = i;
     
            //we need to check the remaining elements
            for(j=i+1;j<size;j++)
            {
                //compare each element and get the minimum element's position
                if(arr[j]<arr[min_pos])
                {
                    min_pos = j;
                }
            }
     
            //now 'min_pos' contains the position with minimum element
            //so we swap the elements
            swap(&arr[i],&arr[min_pos]);
        }
    }
     
    // driver function to test the above function
    int main(void)
    {
        int i;
        int arr[10] = {3, 4, 7, 1, 10, 8, 2, 22, 99, 50};
     
        selectionSort(arr,10);
     
        printf("SORTED array:- ");
        for(i=0;i<10;i++)
            printf("%d ",arr[i]);
     
        return 0;
    }
    时间复杂度:O(n2)
  • 相关阅读:
    资源积累二
    给页面减减肥!
    需求决定设计,设计来源于需求
    项目经理是这样当的
    项目经理之我思员工能动性
    实现性能目标的几种方法
    大项目中项目经理的作用(转自csdn)
    atlas学习实践系列之三(远程web services调用)
    窥视设计模式之组合模式(composite)
    FredCK.FCKeditorV2和vs2005中RequiredFieldValidator配合使用的问题
  • 原文地址:https://www.cnblogs.com/programnote/p/4724676.html
Copyright © 2011-2022 走看看