排序算法--选择排序之简单选择排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/keheinash/article/details/53540812

在待排序记录中,选择一个最小的数,和第一个记录交换位置,在剩下n-1个的记录中选择最小的和第二个记录交换,依次类推,最终可以得到一个有序的序列。

这里写图片描述

代码:

#include <string.h>
#include <malloc.h>
#include <iostream>

using namespace std;

void printArray(int a[], int n){
    for(int j= 0; j < n; j++){  
            cout<<a[j] <<" ";  
    }  
        cout<<endl;
}

int SelectKey(int a[], int n, int i){
    int k = i;
    for(i = i + 1; i < n; i++){
        if(a[i] < a[k]){
            k = i;
        }
    }
    return k;
}

void SimpleSelectSort(int a[], int n){
    int kidx = 0;
    int tmp;
    for(int i = 0; i < n; i++){ 
        kidx = i;
        kidx = SelectKey(a, n, i);//查找i到n中记录最小的值
        if(kidx != i){//交换位置上的记录
            tmp = a[i];
            a[i] = a[kidx];
            a[kidx] = tmp;
        }
        printArray(a, 10);  
    }
}

int main(){
    int a[10] = {10,2,3,238,7,7,2005,0,412,9};
    SimpleSelectSort(a, 10);
    printArray(a, 10);
}

时间复杂度:O(n^2)
稳定性:不稳定

猜你喜欢

转载自blog.csdn.net/keheinash/article/details/53540812