排序算法1 选择排序

311阅读 0评论2012-11-07 黑曼巴snake
分类:

1. 选择排序算法
 

#include <iostream>
using namespace std;

void selectionSort(int arr[], int n)
{
    int smallIndex;
    int pass, j;
    int temp;

    for (pass = 0; pass < n-1; pass++)
    {
        smallIndex = pass;
        for (j = pass+1; j < n; j++)
            if (arr[j] < arr[smallIndex])
                smallIndex = j;
        if (smallIndex != pass)
        {
            temp = arr[pass];
            arr[pass] = arr[smallIndex];
            arr[smallIndex] = temp;
        }
    }
}

int main()
{
    int arr[15] = {10, 21, 2, 1, 3, 45, 2, 932, 32, 27, 86, 65, 576, 434, 76753};

    int i;
    
    cout << "Original array" << endl;
    for (i = 0; i < 15; i++)
        cout << arr[i] << " ";
    cout << endl << endl;

    
    selectionSort(arr, 15);

    cout << "Sorted array" << endl;
    for (i = 0; i < 15; i++)
        cout << arr[i] << " ";
    cout << endl;

    return 0;
}

上一篇:教你如何提升你的气质(不看也许对你没有什么损失,但看了你一定会受益匪浅!!!)
下一篇:排序算法2 插入排序