【實例描述】
本實例實現選擇排序算法,核心思想是首先選取當前最小值的位置及值,與其後各個元素相比,如果還有最小元素,則交換位置,直到到達數組最末尾,
【實現過程】
定義數組a[M],定義函數SelectSort()用於選擇排序算法,代碼如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
#define M 11
void SelectSort(int a[])//定義選擇排序函數
{
cout << "排序過程:" << endl;
int pos;//目前最小的數字的位置
int temp;//temp存最小數字
for (int i = 0; i < M; i++)
{
pos = i; //最小值位置
temp = a[i];//最小值
for (int j = i + 1; j < M; j++) //查找最小的字符
{
if (a[j] < temp)//新的最小值出現
{
pos = j;//新的最小字符的位置
temp = a[j];
}
}
a[pos] = a[i];//交換元素
a[i] = temp;//最小值置於最低位
for (int k = 0; k < M; k++)
cout << a[k] << " ";
cout << endl;
}
}
void main()
{
cout << "--------------選擇排序--------------" << endl;
int a[M] = { 1110,209,386,768,185,247,606,230,834,54,12 };
cout << "排序之前的元素:\n";
for (int i = 0; i < M; i++) //循環排序前數組
cout << a[i] << " ";
cout << endl;
SelectSort(a);//選擇排序法
cout << "排序結果:\n";
for (int i = 0; i < M; i++)
cout << a[i] << " ";//循環排序後數組
cout << endl;
getchar();
}