分析算法步骤: 1、暂定元素排列第0个为最小值,下标为min; 2、然后从左往右依次扫描,与min的关键字比较,若比min的更小,则更新min下标为当前下标; 3、并且把先前的最小值与当前找到目标的元素交换位置。
1#include<iostream> 2using namespace std; 3 4void Swap(int &a, int &b) 5{ 6 int temp = a; 7 a = b; 8 b = temp; 9} 10 11void SelectSort(int arr[],int n) 12{ 13 int i = 0, j = 0, min = 0; 14 for(i; i< n - 1; i++) 15 { 16 min = i; //1、 17 for(j = i + 1; j < n; j++) 18 { 19 if(arr[j] < arr[min]) 20 { 21 min = j; //2、 22 } 23 } 24 if(min != i) 25 { 26 Swap(arr[min], arr[i]); //3、 27 } 28 } 29} 30 31 32int main(void) 33{ 34 int arr[7] = {6,5,4,3,2,1,0}; 35 SelectSort(arr, 7); 36 int i = 0; 37 for(i; i < 7; i ++) 38 { 39 cout<<arr[i]; 40 } 41 return 0; 42} 43
接下来
1g++ -c seelcctSort.cpp
1g++ selectSort.o -o selectSort
把算法步骤写在上面分析,序号都对应在代码相应行了。 害,想来想去还是把主函数加上吧,居然时间长了不会写了。。。(猛男哭泣呜呜呜)
